Repository navigation
fix(#4927): refcount the JVM-wide PageManager lifecycle - #5070
Conversation
The page manager's start/stop keyed on ACTIVE_INSTANCES.isEmpty() - a check-then-act racing across DatabaseFactory instances (open/create synchronize on the factory, the map is static, and registration happens only AFTER database.open() completes): - Race 1: T1 closes the last instance of DB-A and nulls the shared flush thread while T2's open of DB-B is mid-flight (created, not yet registered) - DB-B then NPEs on its first cache miss or its scheduled pages are never flushed. - Race 2: two opens both observe the map empty and both call the unsynchronized configure() - two flush threads, one leaked with queued pages. - Bonus, same defect class: the GlobalConfiguration PROFILE setter calls configure() at configuration time and the old code STARTED a flush thread for zero open databases, leaking it until the next transition. Fix as the issue proposed: acquire()/release() refcounting under one global lifecycle lock. Every open/create acquires (startup on 0 -> 1, BEFORE the database is constructed, so an in-flight open holds a reference before it registers); every close releases (teardown on 1 -> 0); a failed open releases its reference, preserving the #4991 no-leak guarantee. configure() becomes a reconfigure that no-ops at refcount zero; close() stays as the force-teardown test/emergency API and resets the counter. Over-releases clamp at zero. Red-first: 2 of the 3 new tests fail on the old code (configure() starting a thread with no databases; teardown not keyed to the last release). The third is a 2-thread open/close hammer over two databases asserting no thread ever observes a torn-down manager. Regression: engine + database packages green (118 classes, 577 tests, 0 failures), including the #4991 failed-open leak test and the #4928 crash-equivalent close suites.
Not up to standards ⛔🔴 Issues
|
| Category | Results |
|---|---|
| CodeStyle | 3 minor |
🟢 Metrics 10 complexity
Metric Results Complexity 10
NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.
There was a problem hiding this comment.
Code Review
This pull request introduces a reference-counting mechanism for the JVM-wide PageManager lifecycle to resolve race conditions during concurrent database open and close operations. Instead of relying on a racy check of active database instances, DatabaseFactory and LocalDatabase now acquire and release references under a global lock. A potential issue was identified where calling close() multiple times on the same database instance could lead to a double-release of the reference count, which should be guarded.
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.
| if (DatabaseFactory.removeActiveDatabaseInstance(databasePath)) | ||
| GraphAnalyticalView.closeExecutor(); | ||
| PageManager.INSTANCE.close(); | ||
| } | ||
|
|
||
| // #4927: paired with the acquire in DatabaseFactory.open/create - the flush machinery is torn down by | ||
| // the refcount reaching zero, never by the racy "was this the last registered instance" check (an open | ||
| // in flight on another thread holds a reference before it registers, so it can no longer be pulled out | ||
| // from under). | ||
| PageManager.INSTANCE.release(); | ||
| } |
There was a problem hiding this comment.
If close() is called multiple times on the same database instance, closeInternal will execute the code outside the write lock block repeatedly, resulting in multiple calls to PageManager.INSTANCE.release(). This causes a double-release of the refcount. Guarding the close logic using a thread-safe check on openedOn ensures that the PageManager is only released once per database instance.
boolean wasOpen = false;
synchronized (this) {
if (openedOn != 0) {
openedOn = 0;
wasOpen = true;
}
}
if (wasOpen) {
if (DatabaseFactory.removeActiveDatabaseInstance(databasePath))
GraphAnalyticalView.closeExecutor();
// #4927: paired with the acquire in DatabaseFactory.open/create - the flush machinery is torn down by
// the refcount reaching zero, never by the racy "was this the last registered instance" check (an open
// in flight on another thread holds a reference before it registers, so it can no longer be pulled out
// from under).
PageManager.INSTANCE.release();
}|
Tick the box to add this pull request to the merge queue (same as
|
Review:
|
… instance All three review findings were real; the first was a genuine regression in this PR and the reviewer's scenario was exact. 1. RED - redundant double-close stole another database's reference. closeInternal's lambda is documented-idempotent (early-return on !open) but the new release() ran unconditionally after it: dbA.close(); dbA.close(); decremented twice and tore the flush thread down under a still-open dbB - the exact failure this PR exists to eliminate, re-entered through the double-close door. The lambda now reports whether THIS call performed the close, and the whole tail (removeActiveDatabaseInstance, closeExecutor, release) is gated on it - taking the reviewer's suggestion including the arguably-belongs part. 2. ORANGE - acquire() rolls back its increment when startup() throws (e.g. ConfigurationException on negative MAX_PAGE_RAM). Without it the counter wedged at 1 with no flush thread and every later acquire ran against a dead manager the caller's catch could not repair. 3. ORANGE - same-path concurrent open double-release. When registerActiveInstance loses the race it closes the database itself, which (with fix 1) consumes the reference and records it in a per-instance flag; the factory's catch now releases only when the instance did NOT already consume its reference. The lifecycle reference is exactly-once per instance by construction - same pattern as the exactly-once WAL ack from #5012. Red-first: the double-close and startup-failure tests both fail on the pre-review code (1 failure + 1 error). The same-path race has no deterministic repro (it needs two threads between checkForActiveInstance and registerActiveInstance); it is covered by the exactly-once flag construction and the existing hammer test. Regression: engine + database packages green.
Review: refcount the JVM-wide PageManager lifecycle (#4927)Reviewed the full diff plus the surrounding lifecycle code (
The A few observations, none of them blockers: 1.
|
…tance CAS Corrects the previous commit, which was pushed with a FAILING broad battery (325/600) - a process failure on my side: the verification ran in a command chain that committed and pushed regardless of the result. The regression it contained: gating the WHOLE close tail on 'this call performed the close' broke the kill()-then-close() contract (crash simulation used across the test suite) - a killed database reaches close() with open == false, so it was never UNREGISTERED from ACTIVE_INSTANCES, and one leaked registration cascaded into every subsequent test failing the active-database check. The corrected composition keeps each property where it belongs: - removeActiveDatabaseInstance/closeExecutor run UNCONDITIONALLY, as before this PR: unregistration is naturally idempotent (false on the second call) and a killed database must still unregister. - The lifecycle release is EXACTLY ONCE per instance via an AtomicBoolean compareAndSet - a redundant double-close cannot steal another database's reference (the #5070 review's regression), two RACING closes cannot double-release either (the volatile flag alone could), and the same-path open-race loser closed by registerActiveInstance is still seen by the factory's catch through the flag. All five lifecycle tests green including both red-first review tests; full battery: engine + database packages + kill/recovery/leak suites = 611 tests, 0 failures, BUILD SUCCESS verified BEFORE this push.
Review: refcount the JVM-wide PageManager lifecycle (#5070)Thanks for this - the refcount design is the right fix for the 1. Test isolation against the JVM-wide singleton (medium)
Consider normalizing the starting state, e.g. a 2.
|
…ation 1. configure() no longer performs a live shutdown+startup swap when databases are open: the hot paths read flushThread/readCache without the lifecycle lock (and the fields are non-volatile), so a concurrent flush during a profile change could NPE on the transient null. A live profile change is now refused with a WARNING telling the operator to set the profile before opening databases; the refcount-0 case remains a no-op (next acquire reads fresh settings). New regression test pins that the live flush thread survives configure() untouched (isSameAs + isAlive). 2. removeActiveDatabaseInstance is keyed to the instance (two-arg ConcurrentHashMap.remove): when registerActiveInstance closes a same-path open-race LOSER, the loser's close no longer removes the WINNER's still-live mapping (which orphaned the winner from the registry and let a third open of the same path pass checkForActiveInstance). Pre-existing, adjacent, taken as suggested. The GAV-executor gate keeps its map-emptiness return semantics; the one test caller updated. Full battery verified BEFORE this push: engine + database packages, 601 tests, 0 failures, BUILD SUCCESS.
…note; shutdown null-guard Round 3 raced the round-2 push - its points 3 (live-configure window) and 4 (race loser unregistering the winner) were already fixed there. The remaining points, taken: 1. The lifecycle tests normalize the process-global refcount to a known zero baseline in @beforeeach (force-reset via close()), so the assertions are not order-dependent on another test in the same fork leaking an open database or a kill() without its paired close(). 2. kill() now documents the invariant the refcount rests on: it deliberately does NOT release the lifecycle reference - the documented kill-then-close contract relies on the following close() releasing it (exactly once via the CAS, with open == false). A kill() never followed by close() pins the manager open. Minor: shutdown() null-guards readCache (close() is a reachable test/emergency API and may run before any startup()); the create() constructor-call line wrap fixed. Focused suites green: lifecycle 6/6 (with the new baseline), flush robustness, factory, commit ordering.
Review: fix(#4927): refcount the JVM-wide PageManager lifecycleThorough, well-documented change. The core design - a single A few observations, mostly for confirmation rather than blockers: 1. The sibling teardown (
|
Review: refcount the JVM-wide PageManager lifecycle (#4927)Nice work. The refcount-under-one-lock design is the right fix for the A few points, mostly minor: 1. Misplaced Javadoc on
|
…umented; PROFILE caller verified The two points the reviewer wanted before merge, plus the hardening notes: 1. GraphAnalyticalView.closeExecutor: the stale 'alongside PageManager.INSTANCE.close()' doc is rewritten, and both the doc and the closeInternal call site now state that the executor teardown STAYS on the map-emptiness heuristic deliberately - unlike the flush thread, a shutdown executor lazily re-creates itself on the next getExecutor(), so the mid-flight-open race self-heals instead of failing. 2. flushThread/readCache non-volatile publish: the lifecycle invariant is now documented on the fields - written only under LIFECYCLE_LOCK during the 0->1 / 1->0 transitions, read lock-free ONLY because a reader implies refcount > 0, so no transition can run concurrently; make them volatile and re-audit if that ever changes. 3. Live-PROFILE caller verified as requested: the only production setter is the Console at startup (Console.java:113), and it sets 'low-cpu' - the branch that never called configure() at all. No path sets PROFILE after opening a database. 4. Test-isolation fragility acknowledged (the @beforeeach force-reset from round 3 pins the baseline; the coupling to the singleton is inherent). 5. close() javadoc now states force-teardown is only safe with no open database (a live database's eventual release would tear down the NEW manager under a later acquire). Lifecycle suite 6/6, factory suite green.
…rtial-profile warning; idempotency notes 1. My round-3 kill() note was placed AFTER the @OverRide annotation - not attached to the member by the Javadoc tool and duplicating the existing block. Merged into the proper block above the annotation. 2. The live-profile WARNING now states the actual consequence: the profile was PARTIALLY applied (async/HTTP/queue settings changed, page manager sizing did not) - discoverable instead of a vague refusal. 3. closeExecutor() idempotency confirmed (early-return on null/isShutdown under its class lock) and noted at the double-close-reachable call site. 4. The lifecycle test class declares its singleton dependency via @ResourceLock('PageManager.INSTANCE') plus a comment: the force-reset baseline must never run concurrently with a class holding an open database. 5. Nit (field placement) left as-is: moving the declaration away from the closeInternal it documents would trade a style point for locality. Lifecycle suite 6/6, factory green.
Review: fix(#4927) refcount the JVM-wide PageManager lifecycleReviewed the full diff and traced the lifecycle paths against
The A few points: 1. Duplicated / misplaced Javadoc on
|
|
Code Review: refcount the JVM-wide PageManager lifecycle (#4927) Reviewed the full diff and traced the lifecycle interleavings against the source. This is a high-quality, well-reasoned fix. The refcount-under-a-single-lock model is the right shape for the defect, the pairing is balanced across every path I could construct, and the tests pin the contract deterministically (the correct way to test what were originally pure races). The inline Correctness - traced and confirmed
Minor observations (non-blocking)
Test coverage Strong. Red-first on the two lifecycle-divorced-from-DB-count defects, a 2-thread open/close hammer for the race, plus targeted regressions for each 5070-review fix. The @ResourceLock("PageManager.INSTANCE") + force-reset @beforeeach correctly acknowledge the process-global singleton dependency under sequential surefire. Performance / Security No concerns. The lock is taken only on lifecycle transitions (open/create/close), never on the read/flush hot paths, so no added contention. No security surface touched. Verdict: LGTM. The items above are documentation/edge-case polish, not blockers. Careful work on a genuinely tricky concurrency defect. Note: reviewed statically and traced the interleavings by hand; I did not run the full build/test suite in this session. |
…y, release-note sentence The round validated the whole lifecycle design (calling the instance-keyed unregistration 'a genuine bug fix beyond the refcount work') and left five one-line nits; taken: 1. getStats() comment no longer claims configure() populates readCache/flushThread - startup() on the 0 -> 1 acquire does. 2. shutdown() nulls flushThread in a finally, so an interrupt during teardown cannot leave a stale dead reference at refcount 0. 4. The release note now covers BOTH profile cases: no thread started with zero databases, and the live-profile refusal (page manager keeps its sizing; set the profile before opening). Acknowledged: (3) the cross-thread visibility of startup() writes leans on the database-publication happens-before - documented, stays on the radar; (5) the PR body test count is corrected separately via gh. Lifecycle 6/6, flush robustness green.
|
Review: refcount the JVM-wide PageManager lifecycle (#4927) Solid fix. Replacing the ACTIVE_INSTANCES.isEmpty() check-then-act with a refcount under a single LIFECYCLE_LOCK, acquiring BEFORE the database is constructed, is the right shape: it closes the mid-flight-open window the old heuristic left open, and the exactly-once release via AtomicBoolean.compareAndSet cleanly handles double-close, the same-path open-race loser, and kill-then-close. The red-first tests and the commit history show the tricky interleavings (double-close stealing a reference, startup-failure wedging the counter, unregister-must-stay-unconditional for kill()) were each found and fixed. I verified the compilation surface: no stale callers of the old single-arg removeActiveDatabaseInstance or the removed stopPageManagerIfNoActiveInstance remain, and isPageManagerReferenceReleased() is package-private within com.arcadedb.database, reachable from DatabaseFactory. A few points, none blocking: 1. flushThread / readCache non-volatile publication (minor, hardening). The lifecycle invariant is documented well (PageManager.java:68): written only under LIFECYCLE_LOCK on the 0->1 / 1->0 transitions, read lock-free because a reader implies refcount > 0. The cross-thread visibility of the startup() writes leans on the database-publication happens-before (a query thread receives the DB via the ConcurrentHashMap / thread-start, which carries the prior flushThread write). That holds today, but marking both fields volatile would remove the "re-audit if this ever changes" footgun for effectively zero cost - a volatile read on the flush hot path is negligible next to the ConcurrentHashMap barriers already there. Optional, but it makes invalidation of the invariant a compile-time-visible decision rather than a comment. 2. close() is a public force-teardown that zeroes the refcount. close() resets lifecycleRefCount = 0 and tears down unconditionally. It is documented test/emergency-only and I confirmed no production path calls it (the old production caller stopPageManagerIfNoActiveInstance is now removed). Since INSTANCE is a public singleton, a plugin calling it while databases are open would tear the manager down under them - the javadoc warns about exactly this, so acceptable, but consider whether it needs to stay public vs. package-private for the test. 3. Test isolation on the process-global singleton. PageManagerLifecycleRefCountTest force-resets the singleton in @beforeeach and guards with @ResourceLock("PageManager.INSTANCE") + sequential surefire. This is inherently fragile (a class-level parallel surefire config would break it), but the coupling is intrinsic to a JVM-wide singleton and the comments call it out honestly. Fine as-is. 4. Stale comments in adjacent tests (cosmetic). PageManagerReadCacheRamAccountingTest.java:53 and Issue4544FlushIndexIdentityTest.java:53 still reference PageManager.configure() picking up config; that reading now happens in startup() (invoked from acquire() on the first open). Functionally unchanged, but the comments are now slightly misleading. 5. Partial-profile warning. configure() is reached only from the low-ram profile branch (GlobalConfiguration.java:130). The new "PARTIALLY applied" warning on a live profile change is a nice, discoverable behavior; and since the only runtime PROFILE setter (Console at startup, low-cpu) never calls configure(), the warning path will not fire spuriously in normal operation. Overall: correct, well-tested, and thoroughly reasoned. Recommend merge after considering point 1 (volatile) and the cosmetic comment fixes. |
…mments; close() visibility decided 1. flushThread and readCache are now volatile - taken after three review rounds converged on it with a sound cost argument (a volatile read is negligible next to the ConcurrentHashMap barriers already on these paths). The lifecycle-invariant comment stays as the primary reasoning (a reader implies refcount > 0, so no transition runs concurrently); the volatile removes the reliance on the external database-publication happens-before for cross-thread visibility of the startup() writes and makes invalidating the invariant a visible decision. 2. close() STAYS public - decided, not overlooked: it was public API before this PR and CLAUDE.md mandates backward compatibility; embedded users may call it at shutdown. The javadoc already carries the only-safe-with-no-open-database warning. 3. The two stale test comments referencing configure() as the config pickup point now name startup() on the first acquire. Points 3 (test isolation honesty) and 5 (warning behavior) were the reviewer's own confirmations. Focused suites green: lifecycle 6/6, RAM accounting, flush-index identity, flush robustness.
|
Review: fix(#4927) refcount the JVM-wide PageManager lifecycle Thorough read of the whole diff plus the surrounding call sites (DatabaseFactory.open/create, LocalDatabase.closeInternal/kill, GlobalConfiguration PROFILE setter, PageManager). Overall this is a high-quality, carefully-reasoned concurrency fix with strong tests. The core design is sound:
I verified every production caller now uses acquire/release (only configure() remains, from the low-ram PROFILE branch), LocalDatabase is constructed exclusively inside DatabaseFactory (so every instance has a paired acquire), and close() is now test/emergency-only. LowRamProfileTest still passes because it asserts on GlobalConfiguration values with no DB open (refcount 0, so configure() no-ops). Nice red-first discipline (2 tests fail on old code) and the 2-thread hammer is a good addition. Minor / non-blocking:
Nit: the review-provenance comments are genuinely helpful for such a subtle fix, though quite verbose inline; some might live better in the PR/issue. Subjective - I lean toward keeping them given the trap density. Nothing blocking. The concurrency reasoning holds up under inspection and the test coverage (double-close, startup-failure rollback, live-configure refusal, concurrent hammer, multi-db survival) matches the described failure modes. Nice work. |
Round 9 confirmed 'nothing blocking' with one legitimate style catch: the FQNs my earlier review-round additions inlined in PageManagerLifecycleRefCountTest (GlobalConfiguration, assertThatThrownBy, ResourceLock, BeforeEach) now use imports per CLAUDE.md. The other notes were confirmations or already-decided items: the live-profile refusal is release-noted and no runtime flow sets a profile post-open (verified in round 4: the only production setter is the Console at startup); the shutdown-under-lock stall surface is pre-existing (the old close() joined too) and noted; the sequential-surefire assumption is documented on the test. Lifecycle suite 6/6.
Not up to standards ⛔🔴 Issues
|
| Category | Results |
|---|---|
| CodeStyle | 3 minor |
🟢 Metrics 10 complexity
Metric Results Complexity 10
🟢 Coverage 94.00% diff coverage · -7.23% coverage variation
Metric Results Coverage variation ✅ -7.23% coverage variation Diff coverage ✅ 94.00% diff coverage Coverage variation details
Coverable lines Covered lines Coverage Common ancestor commit (852e924) 135124 100760 74.57% Head commit (bd9b6e2) 166954 (+31830) 112422 (+11662) 67.34% (-7.23%) 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 (#5070) 50 47 94.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.
|
Review: refcount the JVM-wide PageManager lifecycle (issue #4927) Overall this is a well-reasoned, high-quality fix. The refcount-under-a-single-lifecycle-lock model correctly replaces the racy What is correct and well done
Minor / non-blocking
Behavior change to flag for release notes Nit Nice work - the reasoning is easy to follow and the tests pin the contract rather than the (unreproducible) races. |
…nsistency
Round 10 ('none blocking') caught the internal inconsistency round 8
created: maxRAM and freePageRAM share the exact write-in-startup /
read-lock-free shape that motivated making flushThread/readCache volatile,
so the same treatment applies - two words, closing the consistency gap in
the documented invariant.
Declined again, with the same reasoning as round 8: renaming/narrowing
close() would break the public API for embedded users (CLAUDE.md mandates
backward compatibility); the javadoc carries the warning. The kill()
cross-test fragility and the release-note emphasis were already addressed
in rounds 3-8; comment-trimming is deferred to post-merge cleanup.
Lifecycle 6/6, RAM accounting green.
|
Review: fix(#4927) refcount the JVM-wide PageManager lifecycle I traced the lifecycle end-to-end ( What is solid
Things worth confirming / minor
Overall a high-quality, well-tested fix with rationale captured directly in the code. Nice work on the acquire-before-construct ordering and the exactly-once release accounting. |
…mented; field alignment The round endorsed the full design after an end-to-end trace. Two items taken: shutdown() now documents the load-bearing invariant that the flush thread must never call a lifecycle method (it is joined under LIFECYCLE_LOCK - a call back into acquire/release/configure/close would self-deadlock; verified true today), and the volatile insertions' column-alignment breakage is fixed. Points 2 and 3 were the reviewer's own confirmations of decided items. Lifecycle suite green.
Review: refcount the JVM-wide PageManager lifecycle (#4927)I traced the refcount protocol end-to-end through Correctness (verified)
Behavior change worth flagging for release notesThe Minor notes (non-blocking)
Test coverageStrong. Six focused tests covering the config-no-DB no-op, close-one-of-two survival, the concurrent hammer, redundant double-close, startup-failure rollback, and live-configure refusal - with Nice work - the invariants are documented well enough that the next person touching this lifecycle won't have to reverse-engineer them. |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #5070 +/- ##
============================================
- Coverage 65.58% 65.58% -0.01%
Complexity 842 842
============================================
Files 1687 1687
Lines 135124 135151 +27
Branches 28907 28912 +5
============================================
+ Hits 88627 88639 +12
- Misses 34401 34409 +8
- Partials 12096 12103 +7 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…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.
… instance All three review findings were real; the first was a genuine regression in this PR and the reviewer's scenario was exact. 1. RED - redundant double-close stole another database's reference. closeInternal's lambda is documented-idempotent (early-return on !open) but the new release() ran unconditionally after it: dbA.close(); dbA.close(); decremented twice and tore the flush thread down under a still-open dbB - the exact failure this PR exists to eliminate, re-entered through the double-close door. The lambda now reports whether THIS call performed the close, and the whole tail (removeActiveDatabaseInstance, closeExecutor, release) is gated on it - taking the reviewer's suggestion including the arguably-belongs part. 2. ORANGE - acquire() rolls back its increment when startup() throws (e.g. ConfigurationException on negative MAX_PAGE_RAM). Without it the counter wedged at 1 with no flush thread and every later acquire ran against a dead manager the caller's catch could not repair. 3. ORANGE - same-path concurrent open double-release. When registerActiveInstance loses the race it closes the database itself, which (with fix 1) consumes the reference and records it in a per-instance flag; the factory's catch now releases only when the instance did NOT already consume its reference. The lifecycle reference is exactly-once per instance by construction - same pattern as the exactly-once WAL ack from #5012. Red-first: the double-close and startup-failure tests both fail on the pre-review code (1 failure + 1 error). The same-path race has no deterministic repro (it needs two threads between checkForActiveInstance and registerActiveInstance); it is covered by the exactly-once flag construction and the existing hammer test. Regression: engine + database packages green. (cherry picked from commit 60caa57)
…tance CAS Corrects the previous commit, which was pushed with a FAILING broad battery (325/600) - a process failure on my side: the verification ran in a command chain that committed and pushed regardless of the result. The regression it contained: gating the WHOLE close tail on 'this call performed the close' broke the kill()-then-close() contract (crash simulation used across the test suite) - a killed database reaches close() with open == false, so it was never UNREGISTERED from ACTIVE_INSTANCES, and one leaked registration cascaded into every subsequent test failing the active-database check. The corrected composition keeps each property where it belongs: - removeActiveDatabaseInstance/closeExecutor run UNCONDITIONALLY, as before this PR: unregistration is naturally idempotent (false on the second call) and a killed database must still unregister. - The lifecycle release is EXACTLY ONCE per instance via an AtomicBoolean compareAndSet - a redundant double-close cannot steal another database's reference (the #5070 review's regression), two RACING closes cannot double-release either (the volatile flag alone could), and the same-path open-race loser closed by registerActiveInstance is still seen by the factory's catch through the flag. All five lifecycle tests green including both red-first review tests; full battery: engine + database packages + kill/recovery/leak suites = 611 tests, 0 failures, BUILD SUCCESS verified BEFORE this push. (cherry picked from commit fe2335b)
…ation 1. configure() no longer performs a live shutdown+startup swap when databases are open: the hot paths read flushThread/readCache without the lifecycle lock (and the fields are non-volatile), so a concurrent flush during a profile change could NPE on the transient null. A live profile change is now refused with a WARNING telling the operator to set the profile before opening databases; the refcount-0 case remains a no-op (next acquire reads fresh settings). New regression test pins that the live flush thread survives configure() untouched (isSameAs + isAlive). 2. removeActiveDatabaseInstance is keyed to the instance (two-arg ConcurrentHashMap.remove): when registerActiveInstance closes a same-path open-race LOSER, the loser's close no longer removes the WINNER's still-live mapping (which orphaned the winner from the registry and let a third open of the same path pass checkForActiveInstance). Pre-existing, adjacent, taken as suggested. The GAV-executor gate keeps its map-emptiness return semantics; the one test caller updated. Full battery verified BEFORE this push: engine + database packages, 601 tests, 0 failures, BUILD SUCCESS. (cherry picked from commit f8eb322)
…note; shutdown null-guard Round 3 raced the round-2 push - its points 3 (live-configure window) and 4 (race loser unregistering the winner) were already fixed there. The remaining points, taken: 1. The lifecycle tests normalize the process-global refcount to a known zero baseline in @beforeeach (force-reset via close()), so the assertions are not order-dependent on another test in the same fork leaking an open database or a kill() without its paired close(). 2. kill() now documents the invariant the refcount rests on: it deliberately does NOT release the lifecycle reference - the documented kill-then-close contract relies on the following close() releasing it (exactly once via the CAS, with open == false). A kill() never followed by close() pins the manager open. Minor: shutdown() null-guards readCache (close() is a reachable test/emergency API and may run before any startup()); the create() constructor-call line wrap fixed. Focused suites green: lifecycle 6/6 (with the new baseline), flush robustness, factory, commit ordering. (cherry picked from commit baba465)
…umented; PROFILE caller verified The two points the reviewer wanted before merge, plus the hardening notes: 1. GraphAnalyticalView.closeExecutor: the stale 'alongside PageManager.INSTANCE.close()' doc is rewritten, and both the doc and the closeInternal call site now state that the executor teardown STAYS on the map-emptiness heuristic deliberately - unlike the flush thread, a shutdown executor lazily re-creates itself on the next getExecutor(), so the mid-flight-open race self-heals instead of failing. 2. flushThread/readCache non-volatile publish: the lifecycle invariant is now documented on the fields - written only under LIFECYCLE_LOCK during the 0->1 / 1->0 transitions, read lock-free ONLY because a reader implies refcount > 0, so no transition can run concurrently; make them volatile and re-audit if that ever changes. 3. Live-PROFILE caller verified as requested: the only production setter is the Console at startup (Console.java:113), and it sets 'low-cpu' - the branch that never called configure() at all. No path sets PROFILE after opening a database. 4. Test-isolation fragility acknowledged (the @beforeeach force-reset from round 3 pins the baseline; the coupling to the singleton is inherent). 5. close() javadoc now states force-teardown is only safe with no open database (a live database's eventual release would tear down the NEW manager under a later acquire). Lifecycle suite 6/6, factory suite green. (cherry picked from commit c03ed05)
…rtial-profile warning; idempotency notes 1. My round-3 kill() note was placed AFTER the @OverRide annotation - not attached to the member by the Javadoc tool and duplicating the existing block. Merged into the proper block above the annotation. 2. The live-profile WARNING now states the actual consequence: the profile was PARTIALLY applied (async/HTTP/queue settings changed, page manager sizing did not) - discoverable instead of a vague refusal. 3. closeExecutor() idempotency confirmed (early-return on null/isShutdown under its class lock) and noted at the double-close-reachable call site. 4. The lifecycle test class declares its singleton dependency via @ResourceLock('PageManager.INSTANCE') plus a comment: the force-reset baseline must never run concurrently with a class holding an open database. 5. Nit (field placement) left as-is: moving the declaration away from the closeInternal it documents would trade a style point for locality. Lifecycle suite 6/6, factory green. (cherry picked from commit b8bc444)
…y, release-note sentence The round validated the whole lifecycle design (calling the instance-keyed unregistration 'a genuine bug fix beyond the refcount work') and left five one-line nits; taken: 1. getStats() comment no longer claims configure() populates readCache/flushThread - startup() on the 0 -> 1 acquire does. 2. shutdown() nulls flushThread in a finally, so an interrupt during teardown cannot leave a stale dead reference at refcount 0. 4. The release note now covers BOTH profile cases: no thread started with zero databases, and the live-profile refusal (page manager keeps its sizing; set the profile before opening). Acknowledged: (3) the cross-thread visibility of startup() writes leans on the database-publication happens-before - documented, stays on the radar; (5) the PR body test count is corrected separately via gh. Lifecycle 6/6, flush robustness green. (cherry picked from commit 5322b29)
…mments; close() visibility decided 1. flushThread and readCache are now volatile - taken after three review rounds converged on it with a sound cost argument (a volatile read is negligible next to the ConcurrentHashMap barriers already on these paths). The lifecycle-invariant comment stays as the primary reasoning (a reader implies refcount > 0, so no transition runs concurrently); the volatile removes the reliance on the external database-publication happens-before for cross-thread visibility of the startup() writes and makes invalidating the invariant a visible decision. 2. close() STAYS public - decided, not overlooked: it was public API before this PR and CLAUDE.md mandates backward compatibility; embedded users may call it at shutdown. The javadoc already carries the only-safe-with-no-open-database warning. 3. The two stale test comments referencing configure() as the config pickup point now name startup() on the first acquire. Points 3 (test isolation honesty) and 5 (warning behavior) were the reviewer's own confirmations. Focused suites green: lifecycle 6/6, RAM accounting, flush-index identity, flush robustness. (cherry picked from commit 0243813)
Round 9 confirmed 'nothing blocking' with one legitimate style catch: the FQNs my earlier review-round additions inlined in PageManagerLifecycleRefCountTest (GlobalConfiguration, assertThatThrownBy, ResourceLock, BeforeEach) now use imports per CLAUDE.md. The other notes were confirmations or already-decided items: the live-profile refusal is release-noted and no runtime flow sets a profile post-open (verified in round 4: the only production setter is the Console at startup); the shutdown-under-lock stall surface is pre-existing (the old close() joined too) and noted; the sequential-surefire assumption is documented on the test. Lifecycle suite 6/6. (cherry picked from commit d980f18)
…nsistency
Round 10 ('none blocking') caught the internal inconsistency round 8
created: maxRAM and freePageRAM share the exact write-in-startup /
read-lock-free shape that motivated making flushThread/readCache volatile,
so the same treatment applies - two words, closing the consistency gap in
the documented invariant.
Declined again, with the same reasoning as round 8: renaming/narrowing
close() would break the public API for embedded users (CLAUDE.md mandates
backward compatibility); the javadoc carries the warning. The kill()
cross-test fragility and the release-note emphasis were already addressed
in rounds 3-8; comment-trimming is deferred to post-merge cleanup.
Lifecycle 6/6, RAM accounting green.
(cherry picked from commit 563027c)
…mented; field alignment The round endorsed the full design after an end-to-end trace. Two items taken: shutdown() now documents the load-bearing invariant that the flush thread must never call a lifecycle method (it is joined under LIFECYCLE_LOCK - a call back into acquire/release/configure/close would self-deadlock; verified true today), and the volatile insertions' column-alignment breakage is fixed. Points 2 and 3 were the reviewer's own confirmations of decided items. Lifecycle suite green. (cherry picked from commit bd9b6e2)
…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)
The last HIGH-severity finding of the 2026-07 engine audit (#4962).
The defect
The JVM-wide PageManager started/stopped on an
ACTIVE_INSTANCES.isEmpty()check-then-act spanning factory instances (open/create synchronize on the factory, the map is static, and registration happens only afterdatabase.open()completes):configure()- two flush threads, one leaked with queued pages.GlobalConfigurationPROFILE setter callsconfigure()at configuration time, and the old code started a flush thread for zero open databases, leaking it until the next lifecycle transition.The fix (as the issue proposed)
acquire()/release()refcounting under one global lifecycle lock: startup on 0->1 (acquired before the database is constructed, so an in-flight open holds a reference before it registers), teardown on 1->0, over-releases clamped. A failed open releases its reference, preserving the #4991 no-leak guarantee.configure()becomes a reconfigure that no-ops at refcount zero;close()stays as the force-teardown test API and resets the counter.Verification
Red-first: 2 of the (now 6) new tests fail on the old code (
configure()starting a thread with no databases; teardown not keyed to the last release); the third is a 2-thread open/close hammer over two databases. Regression: engine + database packages green (118 classes, 577 tests, 0 failures), including the #4991 failed-open leak test and the #4928 crash-equivalent close suites.Conflict risks
None expected: touches
PageManagerlifecycle methods,DatabaseFactoryopen/create, and one line inLocalDatabase.closeInternal- no overlap with the open PRs #5060/#5062.