Skip to content

fix(#8626): a sync forces only the data files written since their last fsync - #8630

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

lvca merged 1 commit into
mainfrom
fix/8626-clean-close-skip-fsync

Conversation

@lvca

@lvca lvca commented Sep 29, 2026

Copy link
Copy Markdown
Member

Closes #8626

Problem

LocalDatabase.close() calls FileManager.syncFiles(), which ran force(true) on every data file before deleting the WAL, whether or not anything had been written to it. Each call still costs a device cache flush, about 0.5 ms per bucket or index file on an NVMe drive. So a read-only open + close of a database with 100 indexed types took about 100 ms.

Fix

The issue proposes a per-file dirty flag or skipping syncFiles() when no transaction committed. This PR uses a per-file flag with three states, which answers both questions in the issue:

  • PaginatedComponentFile tracks what it owes the disk since its last successful fsync: SYNC_CLEAN, SYNC_DATA (a page write) or SYNC_METADATA (created, renamed, or unknown after a crash). The protocol has no gap for a concurrent write. A writer raises the state after its bytes reach the channel. A sync claims the state (swaps it to clean) before it forces, and gives it back if the force fails ([storage] Clean close deletes all WAL files even when the preceding data fsync failed #4934), so the next pass retries.
  • syncFiles() forces only the files that owe something. Page writes get fdatasync (force(false)), which also persists the file-size change of an append. Created or renamed files get a full fsync plus one fsync per directory, so their directory entry survives a power loss too. The old code never guaranteed that. The file-level check is better than a database-level "no commit since open" check: a session that writes to 1 file out of 200 syncs only that file, on close and on every WAL rotation.
  • Recovery (related gap, fixed here): recovery replays the WAL straight into the data files and then deleted the WAL at once, without an fsync. A power loss before the next clean close lost the recovered pages. Now recovery marks every file unsynced, because it is not known what the crashed process wrote. It then forces the files before it deletes the WAL. If that fsync fails, the WAL goes to the inactive pool. The rotation drops it only after a later fsync succeeds, and a close that also fails keeps it with the lock file.
  • Restore (related): the extracted files were never fsynced. The first clean close of the restored database used to cover that, and now a read-only session no longer does. Restore now fsyncs every file (each parallel worker syncs its own entry) and the database directory before it reports success.

Nothing else writes to these files: every page write goes through PaginatedComponentFile.write(), including recovery, HA apply and compaction. SnapshotInstaller already fsyncs what it installs.

Measurements

Clean close p50 after a read-only open, the issue's scenario, one NOTUNIQUE LSM index per type, macOS/APFS:

types before after
0 5.12 ms 1.21 ms
10 4.89 ms 1.43 ms
30 5.18 ms 1.49 ms
100 5.76 ms 1.93 ms

An fsync on a clean file costs little on APFS. The saving is much larger on Linux NVMe (the issue measured 100 ms at 100 types) and on cloud block storage.

Tests

  • PaginatedComponentFileSyncStateTest: state transitions (create, write, reopen, read, rename, recovery mark, unconditional force), and a failed fsync that leaves the file owing the sync.
  • Issue8626CleanCloseFsyncTest: a read-only session close forces 0 files. A write session close forces exactly the files it wrote. Recovery leaves every file synced.
  • Issue8626RecoveryFsyncFailureTest: a recovery whose fsync fails keeps the replayed WAL, and the following close preserves WAL + lock.
  • Mutation checks: with the old force-all syncFiles() the reproducer fails. When recovery drops the WAL without an fsync, both recovery tests fail.
  • Regression: 356 tests (WAL, recovery, fsync, crash, close, checkpoint, compaction, rename, page manager suites), 989 tests (engine, database, index.lsm packages), 122 integration restore/backup tests, all green.

…t fsync

A clean close ran force(true) on every data file of the database before deleting the WAL, whether or not anything had
been written to it. Each call still costs a device cache flush, about 0.5 ms per bucket or index file on an NVMe
drive, so a read-only open + close of a database with 100 indexed types spent about 100 ms persisting nothing.

- PaginatedComponentFile tracks what it owes the disk since its last successful fsync: nothing, data (a page write)
  or metadata (created, renamed, or unknown after a crash). A writer raises the state after its bytes reached the
  channel; a sync claims it before forcing and gives it back when the force fails, so no write can slip between them.
- FileManager.syncFiles() (clean close, WAL rotation) forces only the files that owe something: fdatasync for page
  writes, full fsync plus one fsync per directory for created or renamed files. A read-only session forces nothing.
- Recovery marks every file unsynced (what reached the disk before the crash is unknown) and now forces the data files
  before deleting the WAL it replayed. It used to delete it right away, so a power loss before the next clean close
  lost the recovered pages. If that fsync fails the WAL is kept in the inactive pool, as #4934 does on close.
- Restore fsyncs every extracted file and the database directory before reporting success: a database opened on it
  no longer gets every file forced by its first clean close.
@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 23 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: 18505f83-8582-4d9f-874d-4a94bb1f7ee5

📥 Commits

Reviewing files that changed from the base of the PR and between de966e7 and d59659d.

📒 Files selected for processing (9)
  • engine/src/main/java/com/arcadedb/database/LocalDatabase.java
  • engine/src/main/java/com/arcadedb/engine/FileManager.java
  • engine/src/main/java/com/arcadedb/engine/PaginatedComponentFile.java
  • engine/src/main/java/com/arcadedb/engine/TransactionManager.java
  • engine/src/test/java/com/arcadedb/database/Issue8626RecoveryFsyncFailureTest.java
  • engine/src/test/java/com/arcadedb/engine/Issue8626CleanCloseFsyncTest.java
  • engine/src/test/java/com/arcadedb/engine/PaginatedComponentFileSyncStateTest.java
  • integration/src/main/java/com/arcadedb/integration/restore/format/FullRestoreFormat.java
  • integration/src/main/java/com/arcadedb/integration/restore/format/ParallelZipExtractor.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 22 complexity

Metric Results
Complexity 22

View in Codacy

🟢 Coverage 97.26% diff coverage · -6.06% coverage variation

Metric Results
Coverage variation ✅ -6.06% coverage variation
Diff coverage ✅ 97.26% diff coverage

View coverage diff in Codacy

Coverage variation details
Coverable lines Covered lines Coverage
Common ancestor commit (de966e7) 197713 166254 84.09%
Head commit (d59659d) 230342 (+32629) 179740 (+13486) 78.03% (-6.06%)

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 (#8630) 73 71 97.26%

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 of #8630 (skip fsync of untouched data files on close / WAL rotation)

Overall this is a well-reasoned change. The three-state per-file flag, the write-then-raise / claim-then-force ordering, giving the state back on a failed force (#4934), and the recovery fix (fsync before dropping the replayed WAL) all look correct to me. Tests cover the state machine, the read-only close, and the failing-fsync recovery path, with mutation checks noted in the description. I found nothing blocking. Points below are in rough priority order.

1. Concurrent syncFiles() callers can return true before the fsync they depend on has finished (medium/low)

Claiming the state (swap to clean) before forcing means a second caller that arrives while the first is mid-force() sees SYNC_CLEAN, skips the file and returns true. Previously every caller forced synchronously, so a true return always meant "this data is on disk". Now a true can mean "someone else is currently forcing it, and that force may still fail".

Concretely: the rotation timer thread (cleanWALFiles, TransactionManager.java:1424) is inside pcf.force(); close() calls syncFiles() on another thread, gets true, and deletes the WAL and lock file. If the timer thread fsync then fails, the state is handed back, but the WAL is already gone and the close was reported clean.

It is probably only reachable if the rotation timer is not stopped or drained before the close path syncs. The description says callers wait for the page writes to complete, but not that the syncs themselves are serialized. Either of these would close the gap:

  • make syncFiles() mutually exclusive (a lock in FileManager, cheap now that clean files return immediately), or
  • confirm in a comment that the timer is always cancelled and joined before closeInternal syncs, and that recovery runs before the timer starts.

2. No test for the concurrency protocol (medium/low)

The javadoc on syncState makes a strong claim ("a concurrent write can never be lost between the two sides"), but every test is single-threaded. A small stress test would protect it from later refactors: N writer threads calling write() while a syncer thread loops forceIfModified(); after joining, one more sync must leave the file clean with no exception, and a write that lands after a claim must be seen by the next sync. Tag it @Tag("slow") if it needs to run long.

3. Directory fsync is best-effort but syncFiles() still reports success (low)

FileUtils.forceDirectory swallows failures and returns false (and is a no-op on Windows), and syncFiles() ignores that result. That matches how the rest of the codebase treats directory fsync (#7465), and the state has already been claimed, so a retry would not help. Just flagging that "their directory entry survives a power loss too" in the description is a best-effort guarantee. A one-line note in the syncFiles() Javadoc would make that explicit.

4. Smaller notes

  • PaginatedComponentFile.open(): creating = mode == READ_WRITE && !osFile.exists() is a check-then-act. Fine for the single-owner case, but a file created by another process in that window would only get SYNC_DATA. Harmless in practice.
  • The public force(boolean) now claims and resets the state (and forces metadata for SYNC_METADATA) but does not sync the parent directory like syncFiles() does. A short Javadoc note would help anyone relying on force(true) for a new file name.
  • FileManagerStats.syncedFiles is only consumed by tests. It would also be a useful line in Profiler output for diagnosing the scenario in Clean close fsyncs every data file even when nothing was written since open: about 0.5 ms per bucket or index file #8626.
  • TEST_BEFORE_RECOVERY_REPLAY_HOOK follows the TEST_AFTER_MARKED_CLOSED_HOOK precedent, so that is fine. Issue8626RecoveryFsyncFailureTest.cleanup() swallows any exception from dropping the database; consider logging it so a leaked DB directory does not go unnoticed.
  • Issue8626CleanCloseFsyncTest.cleanCloseSyncsExactlyTheFilesTheSessionWrote compares the syncedFiles delta to the unsynced count observed just before close. If anything else writes a file in between (background compaction, schema save) it could become flaky. Fine today.

Style / CLAUDE.md

Conventions look followed: imports rather than FQNs, final usage, brace-less single-statement if, assertThat(...) style, no stray System.out.

Verdict

Good change with a sensible durability improvement bundled in (recovery and restore). I would address point 1 (or document why it cannot happen) and add the stress test from point 2 before merging; the rest is optional.

@lvca
lvca merged commit 7bb0c11 into main Sep 29, 2026
16 checks passed
@lvca
lvca deleted the fix/8626-clean-close-skip-fsync branch September 29, 2026 04:34
@lvca
lvca restored the fix/8626-clean-close-skip-fsync branch September 29, 2026 04:35
@lvca

lvca commented Sep 29, 2026

Copy link
Copy Markdown
Member Author

Review points addressed in #8631: syncFiles() is now serialized (point 1), with deterministic ordering, concurrent-sync-failure and stress tests (point 2), and the Javadoc notes on the best-effort directory fsync and on force(boolean) (point 3). The Profiler line is left out: its monotonic stats must be carried across a database close, and the counter is diagnostic only.

@codecov

codecov Bot commented Sep 29, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 90.41096% with 7 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.75%. Comparing base (de966e7) to head (d59659d).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
...n/java/com/arcadedb/engine/TransactionManager.java 78.57% 2 Missing and 1 partial ⚠️
...src/main/java/com/arcadedb/engine/FileManager.java 89.47% 0 Missing and 2 partials ⚠️
...va/com/arcadedb/engine/PaginatedComponentFile.java 96.42% 0 Missing and 1 partial ⚠️
.../integration/restore/format/FullRestoreFormat.java 80.00% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@             Coverage Diff              @@
##               main    #8630      +/-   ##
============================================
- Coverage     75.76%   75.75%   -0.01%     
+ Complexity     3421     3417       -4     
============================================
  Files          2055     2055              
  Lines        197713   197772      +59     
  Branches      41603    41622      +19     
============================================
+ Hits         149789   149817      +28     
- Misses        31501    31534      +33     
+ Partials      16423    16421       -2     

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

tae898 added a commit to humemai/arcadedb-embedded-python that referenced this pull request Oct 2, 2026
…a known regression (#89) (#90)

KNOWN_REGRESSIONS becomes a list per situation, and vector gains the October
pin (417314c): only the embedded arm's clean close grows with what is
stored (5.4, 12.5, 88, and 1,400 ms at 10k to 10M; the server's stays near
5 ms), because the lane reads the index statistics before close (BUGS F159,
disclosed on the page as an upper bound) and at this pin a clean close fsyncs
every data file it holds (ArcadeData#8626, fixed by ArcadeData#8630 after the
pin). On the merged October rows the gate now prints vector/lc10m as KNOWN
and reports 0 failures. The entry comes out at the re-pin.


Claude-Session: https://claude.ai/code/session_01Lj5isEaoaGCeaZe5nNoWX4

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
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.

Clean close fsyncs every data file even when nothing was written since open: about 0.5 ms per bucket or index file

1 participant