Skip to content

fix(#8626): serialize syncFiles() so a concurrent sync cannot vouch for an fsync still in flight - #8631

Merged
lvca merged 4 commits into
mainfrom
fix/8626-clean-close-skip-fsync
Sep 29, 2026
Merged

lvca merged 4 commits into
mainfrom
fix/8626-clean-close-skip-fsync

Conversation

@lvca

@lvca lvca commented Sep 29, 2026

Copy link
Copy Markdown
Member

Follow-up to #8630 (issue #8626), addressing the code review on that PR.

Concurrent syncFiles() callers

#8630 made a sync claim a file's pending state (swap it to clean) before forcing it. A second syncFiles() running at the same time found the claimed file clean and returned true while the first fsync was still in flight. This happens in practice: a clean close runs its sync while the WAL rotation timer may be inside its own, and the timer is only stopped by TransactionManager.close() after that. If the timer's fsync then failed, the close had already decided the data was safe and deleted the WAL.

syncFiles() now runs under a dedicated lock. It is not the FileManager monitor, because dropFile() holds that one across I/O. With clean files returning immediately, the lock costs almost nothing. A caller that finds a file clean now knows a completed sync forced it. A failed sync has given the state back, so the next caller forces the file itself and sees the failure.

Tests (PaginatedComponentFileSyncStateTest)

  • writeLandingAfterAClaimIsLeftForTheNextSync: deterministic, using the channel lock. A write that lands after a sync's claim keeps the file marked for the next sync.
  • concurrentSyncWaitsForTheOneInFlightAndSeesItsFailure: a second syncFiles() blocks while the first fsync is in flight, and returns false when that fsync fails. It fails without the lock.
  • concurrentWritesAndSyncsLoseNeitherPagesNorPendingState: 4 writers against a syncer loop. Every page is intact and the file ends settled.

Javadoc

  • syncFiles(): the directory fsync is best effort (as in FileUtils.forceDirectory, and a no-op on Windows).
  • force(boolean): does not force the parent directory.

Regression: 191 engine tests (WAL, recovery, fsync, close, transaction manager, ACID, #8626 suites), all green.

Not done from the review: a Profiler line for syncedFiles. The Profiler's monotonic stats must be carried across a database close (retainedStats), so it is more than a one-line addition, and it is diagnostic only.

…or an fsync still in flight

A sync claims a file's pending state before it forces it. A second syncFiles() running at the same time - a clean
close racing the WAL rotation timer, which the close only stops after its own sync - found the claimed file clean
and returned true while the first fsync was still in flight. When that fsync then failed, the close had already
decided the data was safe and deleted the WAL.

syncFiles() now runs under a dedicated lock (not the FileManager monitor, which dropFile holds across I/O). A caller
that finds a file clean knows a completed sync forced it; a failed sync has given the state back, so the next caller
forces the file itself and sees the failure.

Tests: a deterministic claim-then-write ordering test, a concurrent syncFiles() test where the in-flight fsync fails
(fails without the lock), and a writers-versus-syncer stress test. Javadoc notes that the directory fsync is best
effort and that force(boolean) does not force the directory.
@lvca lvca added this to the 26.10.1 milestone Sep 29, 2026
@lvca lvca added performance storage Storage/paging/WAL engine layer labels Sep 29, 2026
@lvca lvca self-assigned this Sep 29, 2026
@coderabbitai

coderabbitai Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

Next included review available in 3 minutes.

Check out review usage here.

View limit details

Limit details: You’ve used all 4 included reviews currently available.

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

Learn how review limits work.

Review configuration:

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Advanced

Run ID: ed7904d3-389c-494b-909b-a86e7669328b

📥 Commits

Reviewing files that changed from the base of the PR and between 7bb0c11 and 8b4ee85.

📒 Files selected for processing (3)
  • engine/src/main/java/com/arcadedb/engine/FileManager.java
  • engine/src/main/java/com/arcadedb/engine/PaginatedComponentFile.java
  • engine/src/test/java/com/arcadedb/engine/PaginatedComponentFileSyncStateTest.java

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@mergify

mergify Bot commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

This pull request does not currently match the merge queue conditions, so it cannot be queued from here. The box comes back if it matches again.

@codacy-production

codacy-production Bot commented Sep 29, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 0 complexity

Metric Results
Complexity 0

View in Codacy

🟢 Coverage 100.00% diff coverage · -6.05% coverage variation

Metric Results
Coverage variation ✅ -6.05% coverage variation
Diff coverage ✅ 100.00% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (7bb0c11) 197772 166304 84.09%
Head commit (8b4ee85) 230346 (+32574) 179755 (+13451) 78.04% (-6.05%)

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 (#8631) 4 4 100.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.

@claude

claude Bot commented Sep 29, 2026

Copy link
Copy Markdown

Review

The fix is small and correct. I found no blocking issues.

Fix (FileManager.syncFiles())

  • The race is real. forceIfModified() swaps the state to clean before it forces. A second concurrent syncFiles() therefore sees a clean file and returns true while the first fsync is still in flight. A dedicated lock closes that.
  • Using a separate syncLock instead of the FileManager monitor is the right call, because dropFile() holds the monitor across I/O. The comment says so.
  • I grepped the engine and server main sources. syncFiles() is the only production caller of forceIfModified(), so no path bypasses the lock. The three call sites are LocalDatabase:3029, TransactionManager:556 and TransactionManager:1424.
  • I saw no lock-ordering risk. syncLock is taken first, then per-file channelLock. Nothing that holds channelLock calls syncFiles().
  • A failed fsync gives the state back, so the next caller forces the file again and sees the failure. That matches the javadoc.
  • The lock now serializes fsync-heavy passes. A close can wait behind a slow rotation-timer sync, but it had to do that anyway to be correct.

Tests

  • The two deterministic tests are good. They use channelLock queue-length probes instead of sleeps. concurrentSyncWaitsForTheOneInFlightAndSeesItsFailure demonstrably fails without the lock.
  • Minor, possible flake: concurrentWritesAndSyncsLoseNeitherPagesNorPendingState asserts syncer.get(...) is positive ("the syncer must have raced the writers"). On a loaded CI runner, all four writers could finish and writing flip to false before the syncer thread runs its first iteration. The loop would then never execute and forced would be 0. A do { ... } while (writing.get()) loop, or a CountDownLatch that releases the writers once the syncer has run once, would remove that. Even then forced is only positive if the file is still owed a sync when the first iteration runs.
  • awaitBlocked relies on Thread.State.BLOCKED. That is correct for synchronized, so it would need updating if the lock ever becomes a ReentrantLock, which reports WAITING.
  • The reflection helpers (channelLock, channel) follow the existing pattern in this test class. Refactoring breakFile out of the earlier test is a nice cleanup.

Nits

  • The new syncFiles() javadoc is a long multi-paragraph block, and CLAUDE.md prefers short comments. The reasoning is valuable, though, and it would be fine to trim the timer/close narrative to a sentence or two.
  • I have no objection to skipping the Profiler line for syncedFiles. Follow-up scope is reasonable.

The implementation looks good to merge. I would just harden the stress-test assertion above.

…start

The syncer loop was a while loop checked against a flag the main thread flips once the writers are done: on a loaded
runner all four writers could finish before the syncer thread ran once, leaving its forced count at 0. It is now a
do-while, and the writers wait for its first pass, which always forces the created file's metadata.

awaitBlocked also accepts WAITING, so the concurrent-sync test keeps working if the sync lock ever becomes a
java.util.concurrent lock. syncFiles() Javadoc trimmed.
@claude

claude Bot commented Sep 29, 2026

Copy link
Copy Markdown

Review

The change is small and correct for the race it targets. Serializing syncFiles() on a dedicated syncLock is the right fix. It also makes the invariant simple: a caller that sees a file as clean knows a completed sync forced it, and a failed sync has already given the state back. Using a separate monitor rather than the FileManager one, because dropFile() holds that across I/O, is sound. I found no lock-order problem: syncLock is taken first and then channelLock (read), and nothing holding channelLock for write calls syncFiles(). I did not run the tests locally.

Code

  • FileManager.syncFiles() / syncFilesSerialized() look fine. The lock scope includes the directory fsyncs, which is right, since a caller that returns true should also see the directory entries as durable.
  • A small pre-existing gap, worth a follow-up but not a blocker: PaginatedComponentFile.force(int, boolean) returns false without throwing when channel == null. It gives the state back, but forceIfModified() then returns SYNC_CLEAN, so syncFiles() reports true for a file it did not sync. This only matters for a closed file, so it is probably benign, but the new Javadoc wording ("a caller that finds a file clean knows a completed sync forced it") is not strictly true on that path.
  • The public PaginatedComponentFile.force(boolean) also claims the state and is not covered by syncLock. I found no other production callers, so this is fine today. If one appears it can reintroduce the same window, so a note on that method would help.
  • The Javadoc additions are accurate, including "never fails the sync" for the directory fsync (FileUtils.forceDirectory is best effort).

Tests

The tests are deterministic where it matters: they use the channel lock plus getQueueLength() rather than sleeps, and breakFile is a good extraction. concurrentSyncWaitsForTheOneInFlightAndSeesItsFailure covers the actual regression. Nits:

  1. concurrentWritesAndSyncsLoseNeitherPagesNorPendingState: writing.set(false) is not in a finally. If a writer fails and f.get(...) throws, the syncer keeps looping, because the do/while never checks for interruption and forceIfModified() on a clean file does no interruptible I/O. shutdownNow() may then leave a spinning thread for the rest of the JVM life. Setting the flag in a finally avoids that.
  2. That same test calls PaginatedComponentFile.forceIfModified() directly, so it does not exercise the new syncLock. It covers the claim/raise protocol from PR 8630. The name and PR description read as if it covers the serialization, so consider a clarifying comment, or driving it through FileManager.syncFiles() with several syncer threads.
  3. awaitBlocked shares secondThread[0] across threads through a plain array with no happens-before edge. It works in practice because the poll loop retries, but an AtomicReference<Thread> would be cleaner. Treating WAITING as "parked on the sync lock" is also slightly loose. It is fine here, since the task only does synchronized first, but a comment would make the assumption explicit.
  4. Please confirm the runtime of the stress test on CI (1000 pages plus a force loop). It should be quick enough not to need @Tag("slow").

Perf / security

No security concerns. Performance is unchanged in the common case: with clean files the lock is uncontended and each call is one getAndSet per file. Under contention a clean close now waits for an in-flight rotation sync, which is the intent.

Overall this is good to merge once the finally nit in the stress test is addressed. The rest are optional.

…them spinning

- The stress test now drives FileManager.syncFiles() from two syncer threads, so it exercises the sync lock as well as
  the claim/raise protocol, and clears the writing flag in a finally: a failed writer left the syncers looping.
- The concurrent-sync test hands the second thread over through an AtomicReference; awaitBlocked documents why a
  parked thread is one waiting for the sync lock.
- Javadoc: a closed file is skipped by syncFiles() and keeps what it owes; the public force(boolean) claims the state
  outside the sync lock, so it must not run concurrently with a syncFiles() whose result is relied on.
@claude

claude Bot commented Sep 29, 2026

Copy link
Copy Markdown

Review

The fix looks correct and I have no blocking findings. I read the diff and the surrounding FileManager, PaginatedComponentFile, TransactionManager and LocalDatabase code. I did not run the tests.

Correctness

  • Holding one lock across the claim, the force and the give-back on failure removes the window where a second syncFiles() sees a claimed file as clean and vouches for an fsync still in flight. syncFiles() now returns true only after every fsync a completed sync owed has finished.
  • I checked the lock order and found no deadlock risk. cleanWALFiles holds synchronized (inactiveWALFilePool) and then takes syncLock. The clean-close path in LocalDatabase and the recovery path in TransactionManager take only syncLock. Nothing inside syncFilesSerialized() takes the pool monitor or the FileManager monitor, so the order is consistent.
  • Using a dedicated lock instead of the FileManager monitor is the right call, since dropFile() holds that monitor across I/O. The cost is small: clean files return at the getAndSet check.
  • A caller that arrives mid-sync now waits for the whole pass, including every fsync and the directory fsyncs. That is the intended semantics. It means a clean close can block behind a slow rotation pass, which is inherent to the fix.
  • A file whose channel is closed returns SYNC_CLEAN and keeps its state, so syncFiles() reports true. That behaviour already existed and the Javadoc now says so. Because the state is kept, the file still owes the next sync, so nothing is lost.

Nits (non-blocking)

  • synchronized held across blocking I/O pins carrier threads if the engine is ever called from virtual threads on JDK 21-23. A ReentrantLock would avoid that. This is theoretical, because the callers are the timer thread and close, so I would not change it now.
  • force(boolean) is documented as having no production callers and as unsafe to run alongside syncFiles(). If it is truly dead code, consider deleting it or making it package-private. Otherwise a later caller can quietly reintroduce the race this PR closes.
  • awaitBlocked treats any BLOCKED or WAITING state as "waiting for the sync lock". The Javadoc explains why that holds today. If syncFiles() gets more lock-like waits before the sync lock, the test could pass for the wrong reason. It does fail without the lock, as claimed.
  • concurrentWritesAndSyncsLoseNeitherPagesNorPendingState has two syncers spinning on syncFiles() for the whole write phase. The workload is bounded (1000 pages) and has generous timeouts, so I do not expect flakiness. It is CPU-heavy on small CI runners, though. If it shows up as slow, tag it @Tag("slow").

Tests

  • The three tests match the behaviours the PR describes. Coordinating through the channel lock queue (awaitQueued) gives deterministic interleavings without wall-clock assertions, which is in line with CLAUDE.md.
  • breakFile(...) and channelLock(...) use reflection, as the existing test already did, so that is consistent.
  • The tests use assertThat style and no ports, and they have no leftover System.out. The finally blocks shut down the executors and close the FileManager.

LGTM.

…ckage-private

- syncFiles() is held across fsyncs, and the engine runs work on virtual threads: a virtual thread blocked on a monitor
  pins its carrier thread, one parked on a ReentrantLock does not.
- PaginatedComponentFile.force(boolean) claims the pending state outside the sync lock, so a production caller could
  reopen the race syncFiles() closes. Only tests in the package call it: now package-private.
- The concurrent-sync test waits until the second caller is queued on the sync lock itself (hasQueuedThread) instead
  of inferring it from the thread state. It still fails without the lock.
@claude

claude Bot commented Sep 29, 2026

Copy link
Copy Markdown

Review

Overall this is a small, well-reasoned fix and I have no blocking concerns.

What I checked

  • The fix. A claim-then-force protocol needs the callers serialized, otherwise a second caller sees a claimed (clean) file and vouches for an fsync still in flight. Wrapping syncFiles() in a dedicated ReentrantLock fixes exactly that.
  • Lock choice. Not using the FileManager monitor is right, since dropFile() holds it across I/O. ReentrantLock rather than synchronized is also right, because it is held across fsyncs and a virtual thread would pin its carrier on a monitor.
  • Deadlock risk. I checked the three callers (LocalDatabase.java:3029, TransactionManager.java:556 and :1424). None takes the FileManager monitor before syncFiles(), and syncFilesSerialized() never takes that monitor. The only nesting is syncLock then the per-file channelLock, which is consistent, so I see no cycle.
  • Visibility change on force(boolean). I grepped the whole repo. The only remaining callers are tests, and all of them are in com.arcadedb.engine, so narrowing to package-private compiles. No other module is affected.
  • Performance. With clean files returning immediately, the lock is essentially free on the hot path. The only new cost is that a WAL rotation can now wait behind a close's sync (or the reverse), which is the intended behaviour.

Suggestions (non-blocking)

  1. force(boolean) is now test-only. The Javadoc says "only tests call it". If that stays true, consider annotating it as test-only or dropping the production method in favour of a helper in the test. As written, the "must not run concurrently with a syncFiles() whose result is relied on" hazard is documented but not enforced.
  2. Blocking lock(). A rotation-timer thread blocked behind a slow close-time sync is not interruptible. That is probably fine here. If TransactionManager.close() ever needs to stop the timer promptly, lockInterruptibly() would be worth a look.
  3. Test brittleness. The new tests reach into the private channelLock, channel and syncLock fields by reflection. That is acceptable for these deterministic interleavings, but a rename will break them with a NoSuchFieldException rather than a compile error. A one-line comment on the helpers saying so would help the next reader.
  4. Silent skip in syncFiles(). The Javadoc now says a file whose channel is closed is skipped and keeps its state, yet syncFiles() still returns true for it. That is pre-existing and reasonable for dropped files, but for a channel closed mid-database it means "true" does not strictly mean "every pending file was forced". Not a regression from this PR, but worth being aware of.

Tests

The three new tests target the right things:

  • writeLandingAfterAClaimIsLeftForTheNextSync is deterministic.
  • concurrentSyncWaitsForTheOneInFlightAndSeesItsFailure checks that the second caller is queued on the sync lock itself, not merely parked somewhere, which is a good way to avoid a false pass.
  • The stress test is bounded and cleans up in a finally.

There is no raw wall-clock assertion; timeouts are only used as hang detectors, consistent with the CLAUDE.md guidance.

LGTM.

@codecov

codecov Bot commented Sep 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 75.76%. Comparing base (7bb0c11) to head (8b4ee85).

Additional details and impacted files
@@             Coverage Diff              @@
##               main    #8631      +/-   ##
============================================
- Coverage     75.76%   75.76%   -0.01%     
- Complexity     3417     3422       +5     
============================================
  Files          2055     2055              
  Lines        197772   197776       +4     
  Branches      41622    41622              
============================================
- Hits         149849   149839      -10     
- Misses        31510    31523      +13     
- Partials      16413    16414       +1     

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

@lvca
lvca merged commit b8ab990 into main Sep 29, 2026
32 of 35 checks passed
@lvca
lvca deleted the fix/8626-clean-close-skip-fsync branch September 29, 2026 13:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

performance storage Storage/paging/WAL engine layer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant