Repository navigation
feat(#6072): faster full backup - configurable compression level and parallel compression - #6080
Conversation
…compression The full backup deflated every database file at level 9 on the calling thread, which caps it at the ~20-40 MB/s one core sustains. Its duration is also the flush-suspension window that throttles committing threads, so the backup was both slow and disruptive. - `arcadedb.backup.compressionLevel` (default lowered 9 -> 1): measured 3.1x faster for a 7.5% bigger archive on a 1.25 GB database. - `arcadedb.backup.compressionThreads` (default -1 = half the cores, capped at 8): a new ZIP writer that splits each entry into 1 MB chunks, deflates them in parallel with SYNC_FLUSH and concatenates them back in order (the pigz construction). Scaling is near-linear; 27x end to end against the old default. 0 selects the previous single-threaded java.util.zip writer, kept as an escape hatch. - `arcadedb.backup.maxMBPerSecond` (default 0 = unlimited): optional read-side cap. The archive format is unchanged: entries use the streaming form of the ZIP spec (bit 3 + data descriptor) that ZipOutputStream itself emits for a DEFLATED entry of unknown size, with ZIP64 above 4 GB. Old backups restore and new ones restore through the unchanged restore path. All three settings are also exposed on the command line, on the Backup API and in `BACKUP DATABASE ... WITH ...`. Two defects fixed on the way: - `BACKUP DATABASE ... WITH ...` dropped every setting, matching the name against `Expression.toString()` which renders a string quoted; `WITH encryptionKey = '...'` therefore produced an archive in clear. `copy()` dropped the settings map as well. - A backup that failed halfway still reported success: `suspendFlushAndExecute` runs its callback through `CodeUtils.executeIgnoringExceptions`, so the archive was finalized with a valid central directory over a truncated set of entries. The failure is now carried out of the suspension and the partial archive is deleted.
|
Tick the box to add this pull request to the merge queue (same as
|
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 105 |
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.
ReviewWent through the full diff (engine Correctness
Concurrency (per the
|
…ithmetic - A failed backup no longer gets a central directory written at all. `suspendFlushAndExecute` swallows its callback's exception, so a failed backup returns normally and the writer's try-with-resources still finalized the archive before the caller noticed; a `close()` that itself failed in that window would then have replaced the root cause. `BackupArchiveWriter` gains `abort()` - release the resources, do not terminate the archive - and only a backup that actually succeeded is closed. The partial file is still deleted; aborting means that even if the delete cannot happen, what is left has no central directory and no tool will restore from it. Covered by a writer-level test and by an end-to-end one that makes a component file unreadable mid-backup. - `IoThrottler` computes its deadline in exact integer arithmetic instead of via `double`, re-baselining every GB so `totalBytes * 1e9` cannot overflow a long. The baseline moves to the previously computed deadline, so no rounding drift accumulates. - Recorded in the writer's Javadoc that the streaming-data-descriptor + ZIP64 combination is verified against four independent readers (ZipInputStream, ZipFile, Info-ZIP unzip -t and Python zipfile), not only the two JDK ones the tests exercise.
|
Thanks - all three notes addressed. 1. Double-fault during an already-failing backup. Fixed properly rather than papered over. 2. 3. Third-party unzip tools. Fair - the claim was JDK-shaped. Now actually verified, on archives produced by this writer including a 4 GB entry (the streaming-data-descriptor + ZIP64 combination): So four independent readers now: Pushed as 8a75001. |
Review: Parallel backup compression (issue 6072 phase 1)This is a well-engineered change: a real performance problem (deflate level 9 on the calling thread, inside the flush-suspension window) is diagnosed with numbers, fixed with a measured default plus opt-in parallelism, and the archive format contract is preserved (verified against Code quality / correctness
Performance
Security
Test coverage
Nice piece of work overall - the docstrings explaining why (concatenable SYNC_FLUSH deflate streams, the streaming ZIP64 data-descriptor form, the failure-swallowing of suspendFlushAndExecute) make this hand-rolled binary format code much easier to trust and maintain than it would otherwise be. |
Second review round. - The CLI, the Backup API and SQL all validated, but a value arriving from a system property, a configuration file or setValue() bypassed every one of those and reached `new Deflater(level, true)` unchecked - exactly the failure mode parseIntSetting's own docstring says it exists to avoid. BACKUP_COMPRESSION_LEVEL and BACKUP_COMPRESSION_THREADS now carry allowed-value sets via the existing integerRangeAsStrings hook, so an out-of-range value is rejected where it is set, naming the setting, and the previous value is restored. BACKUP_MAX_MB_PER_SECOND deliberately has none: its range is open-ended upwards and any non-positive value simply disables the throttle. The thread bound is now a shared constant so the four surfaces cannot drift apart. - ParallelZipArchiveWriter.release() awaits pool termination before draining the deflater pool. On the abort path a worker interrupted mid-chunk still returns its Deflater in its own finally, which raced with the drain and left it to the JDK cleaner instead of being freed. - The 4GB ZIP64 test gets an explicit 10-minute timeout. It runs in the unit lane, whose only guard is a 60-minute cap on the whole job, and a test moving 4GB is the shape that could eat that budget on a degraded runner. It takes ~2s in practice.
|
Second round addressed - all three points were valid, all three implemented. 1.
The API/CLI upper bound moved from 1024 to a shared 2. 3. 4GB test and the CI budget. Checked: Pushed as 0aa9d83. |
…ackup-phase1 # Conflicts: # docs/release-26.9.1.md
Review: Faster full backup (configurable compression level + parallel compression)I read through the diff in full ( Correctness
Minor / nit
Performance & concurrency
Test coverageVery strong: No blocking issues found. Nice work. |
ReviewWent through the full diff, plus the accompanying test suites ( A few things worth a second look before merge, none of which I'd call blocking given the test coverage described in the PR: 1. EndOfCentralDirectory field truncation when only some zip64 conditions apply ( 2. Root-cause exception can still be shadowed in one path ( 3. Default compression level change is a real behavior change for existing deployments 4. Minor: Test coverage: excellent. The chunk-boundary parameterization ( Performance/concurrency: sizing the default thread pool at half the cores capped at 8, using a dedicated Nice work, this is a thorough, well-benchmarked, and honestly-documented performance change. |
…ring it Third review round. - An unrecognised 'WITH ...' setting name was dropped in silence. That is the same failure mode as the Expression.toString() bug this PR already fixes, reached by a second route: 'WITH encryptionkey = ...' - one wrong character - looks like a request for an encrypted archive and produced a cleartext one. It is now a CommandExecutionException naming the supported settings. Nothing that worked stops working: until the fix in this PR every setting was ignored, so no statement can have depended on one being accepted. - Import java.lang.management.OperatingSystemMXBean in the benchmark instead of writing it fully qualified, per CLAUDE.md. The duplicated int parsing between BackupDatabaseStatement (engine) and BackupSettings (integration) is left as is: engine cannot depend on integration, and routing it through String-typed reflective setters would add public API purely to share eight lines.
|
Third round - thanks. Two of the three acted on, one deliberately not. Fully-qualified Unrecognised Worth being explicit that this is a behaviour change, so it can be vetoed: a statement carrying an unknown setting used to succeed and now fails. I judged the compatibility risk to be nil rather than small - until the fix in this PR, every setting was silently dropped, so no working statement can have depended on one being accepted; the only statements affected are ones that were already not doing what they said. Covered by Duplicated int parsing across the module boundary. Agreed and left as is - engine cannot depend on integration, and the alternative (String-typed reflective setters on One note on local verification: Pushed as 09a9a1c. |
…se from hiding the cause Fourth review round. - The ZIP64 end-of-central-directory branch was untested. It fires when the ARCHIVE passes 4GB, not the entry, which is the common case in production (a few tens of GB of database), and no existing test reached it: a 4GB compressible entry yields a 19MB archive. The new test writes a >4GB archive with both this writer and java.util.zip's into a sink that keeps only the tail, and asserts the end records field by field against the JDK's own bytes. It also settles the encoding question: only the fields that individually overflow carry their sentinel. Verified against the JDK for the same logical archive - it emits the real entry count and the real directory size next to a sentinel directory offset, exactly as this writer does. Asserting against the JDK's bytes rather than against a reading of APPNOTE means the two cannot drift. The test costs no disk: sparse source, level 0 so the 4GB passes through as stored blocks, and nothing is retained but the last 256 bytes. - A failure to close the archive stream could still displace the root cause. `writeArchive` now rethrows the carried failure from inside the callback, so `encryptFile` knows the backup failed and records a close failure as suppressed instead of letting it replace the exception that explains what went wrong. On the success path a close failure still propagates - the last bytes may not have reached the disk, which is the backup's failure. - Release notes carry an explicit upgrade note about the level 9 -> 1 default: archives are ~7.5% larger with no configuration change, and how to keep the old size.
|
Second review of this round (the 22:10 one) - thanks, point 1 was the most useful comment on this PR so far, though not for the reason stated. 1. EOCD field truncation. I checked this against the JDK rather than against APPNOTE, by writing the same logical archive (one entry just over 4GB, level 0 so the archive itself passes 4GB) with So the premise is not right: But the underlying worry was right, for a different reason. The ZIP64 end-of-central-directory branch had no test at all. New test 2. 3. Default level change prominence. Added an explicit upgrade note to the release notes: archives are ~7.5% larger after upgrading with no configuration change, and how to get the old size back ( 4. Cancelled futures not returning buffers to the pool. Agreed, no change - Pushed as 4e7ba74. |
ReviewWent through the full diff, including the hand-rolled ZIP writer, the throttler arithmetic, the two SQL settings bugs, and all four new test files. Overall this is exceptionally well-engineered work: the streaming-data-descriptor / ZIP64 reasoning matches how A few smaller points: 1. 2. 3. Minor test gap: SQL path never exercises an out-of-range numeric setting 4. Nothing above blocks merging; only #1 and #3 seem worth a small follow-up. Nice work on the ZIP64 interop verification (four independent readers) and the concurrency design per the |
ReviewThis is an unusually thorough PR — I read through Code quality / design
Potential issues / nitpicks
Performance
Security
Test coverage
Nothing here rises to "must fix" — the nitpicks are documentation/robustness suggestions, not correctness problems. Nice work. |
…s rejected Fifth review round. Writing the suggested test for the out-of-range SQL path found a real, if minor, defect: the path works, but what the user sees is 'Error on backing up database', with 'compressionLevel must be between 0 and 9, found 20' buried in the cause chain. The settings loop now catches InvocationTargetException itself and surfaces the setter's own message, so a bad value says what was wrong with it. Also from the same review: - The 256 thread bound is a literal in GlobalConfiguration and a constant in BackupSettings, and cannot be shared because the engine module cannot depend on integration. Both sides now say so, and backupThreadBoundMatchesTheGlobalConfiguration fails if they ever drift - a comment asking the next editor to change both is not enforcement. - Documented that writing the central directory outside the read lock and the flush suspension is deliberate, not a side effect of the refactor: it is built purely from the per-entry records collected while the files were read, touches no database state, and keeping it inside would hold writers throttled for one more write per file. - IoThrottler parks in a loop against the absolute deadline instead of once, so a spurious wakeup cannot let a read through early. An interrupt breaks the loop and leaves the flag set rather than being spun through.
|
All four addressed. #3 was the good one - writing the suggested test found a real defect. 3. Out-of-range numeric setting via SQL. You traced it and believed it works. It does work - the value is rejected - but writing the test showed what the user sees is wrong: The reason is buried one level down, because the generic outer 1. Duplicated 256 bound. Correct - my earlier commit message overstated it as "a shared constant"; 2. Central directory now written outside the suspension window. Intentional, and thank you for making me confirm it rather than assume. It is built purely from the per-entry records collected while the files were read - no database state - so nothing about it requires the suspension, and keeping it inside would hold writers throttled for one extra write per file. Now documented in the code so it does not read as an accident. Note the benchmark numbers are unaffected and remain conservative: 4. Pushed as de0b0d1. |
…a.util.zip does
Sixth review round.
- writeCentralDirectoryEntry promoted all three of compressed size, uncompressed size and local
header offset to their sentinel as soon as any one of them overflowed, writing three 8-byte
values into the extra field where one was needed. That is legal and self-consistent, but it is
not what the specification asks for ("the fields MUST only appear if the corresponding record
field is set to 0xFFFFFFFF") and not what ZipOutputStream.writeCEN does - and this writer
already got it right in the end-of-central-directory record, so the two disagreed with each
other. Each field is now promoted on its own. The >4GB entry test asserts the extra field is
8 bytes and identical in length to the one java.util.zip produces for the same entry, so the
reference is the JDK rather than a reading of APPNOTE.
- Documented the thread-confinement invariant next to the buffer pools: they are plain
ArrayDeques because only the addFile thread ever touches them, while the deflater pool is
concurrent because workers do. It is the confinement that is the invariant, not the collection
type, and it would be easy to "fix" one into the other by mistake.
|
This one (the 22:22 review) crossed with my previous reply - answering it separately. Central directory ZIP64 field granularity. You suggested a comment saying the coarse-grained version was deliberate. It was not deliberate, it was an inconsistency, so I have fixed it instead. Promoting all three fields as soon as any one overflows is legal and self-consistent, but it is not what APPNOTE asks for ("the fields MUST only appear if the corresponding record field is set to 0xFFFFFFFF"), it is not what The Buffer-pool thread confinement. Agreed, and it is exactly the kind of invariant someone "fixes" into a bug. Comment added at the field declarations spelling out that the
Pushed as b22a9cc. |
Up to standards ✅🟢 Issues
|
| Metric | Results |
|---|---|
| Complexity | 115 |
🟢 Coverage 92.21% diff coverage · -6.56% coverage variation
Metric Results Coverage variation ✅ -6.56% coverage variation Diff coverage ✅ 92.21% diff coverage Coverage variation details
Coverable lines Covered lines Coverage Common ancestor commit (ec0fc4a) 154818 121131 78.24% Head commit (028008d) 187527 (+32709) 134413 (+13282) 71.68% (-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 (#6080) 398 367 92.21% 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: faster full backup (configurable level + parallel compression) This is a large, unusually well-engineered change (2.6k additions across the archive writer, throttler, settings surface, and ~1,900 lines of new tests). The design write-up and the five self-review-round commits already anticipated most of what a reviewer would flag (unrecognised WITH settings, out-of-range values reaching Deflater unchecked, abort-vs-close semantics, exact throttle arithmetic). Went through the diff file by file; overall this looks solid and ready to merge modulo a few small items below. Correctness
Minor / nitpick
Performance
Security
Test coverage Exceptionally thorough for this kind of change: chunk-boundary matrix (0, 1, n-1, n, n+1, 2n, 2n+1, ...), byte-identical restore across thread counts, parallel-vs-legacy byte equality, the greater-than-4GB archive and greater-than-4GB entry ZIP64 branches each with their own dedicated test and an explicit Timeout, encrypted round trips, SQL surface (including the two defects above), CLI parsing, GlobalConfiguration boundary validation, and a concurrent-write-load restore-consistency test. Nothing stands out as missing. Tagging (@tag("benchmark") on BackupCompressionBenchmark, @timeout on the two multi-GB tests) matches the conventions in CLAUDE.md. Nit
Nothing here blocks merging; the ZIP64 local-header version field is the only item worth double-checking before shipping, and even that is likely a non-issue given the described external verification. |
ReviewI read through the new/changed files in Correctness — hand-traced, no bugs found
Minor / non-blocking nits
Test coverageExcellent — Performance / security
Nice work — this is a thorough, well-documented, and well-tested change. |
…d Info-ZIP interop Seventh review round. The one item flagged as worth double-checking before shipping was the ZIP64 local-header version field. - It is correct, and now asserted rather than argued. A streamed entry's local header keeps "version needed to extract" at 2.0 even when the entry needs ZIP64, because with a data descriptor the sizes are not known when that header is written, so there is nothing to base an upgrade on - ZipOutputStream.writeLOC takes the same branch. The >4GB entry test now reads the field out of both archives and asserts they agree, so the reference is the JDK's bytes. - The Info-ZIP verification was a one-time manual check. It is now a test: it shells out to unzip -t (which inflates and CRC-checks rather than listing) when the binary is on PATH and skips otherwise. Info-ZIP is a genuinely independent implementation, so agreeing with it is worth more than agreeing with the two JDK readers, which share one. It runs on the ordinary fixture rather than a multi-GB archive: the streaming data descriptor is what is unusual and every entry carries one. - The automatic thread count moved into a package-private static taking the core count, so its boundaries can be pinned instead of depending on the machine running the suite. The formula is trivial, which is why it is worth a test: it encodes a deliberate trade that a one-character edit could change with nothing else failing.
|
All four addressed. ZIP64 local-header version field (the one you flagged for double-checking). It is correct, and it is now asserted rather than argued. Info-ZIP verification was manual. Now durable.
Nit on prose-heavy docs. Keeping it - the neighbouring entries in Pushed as eb743d2. |
…eachable check Eighth review round. - The settings loop fell back to Expression.toString() when Expression.value was null. That fallback is the buggy match this PR exists to remove, so a future parser change that stopped populating value would have silently resurrected the cleartext-archive defect instead of failing. It now throws instead of falling back. - The peak-heap breakdown on BACKUP_COMPRESSION_THREADS was wrong in its parts while right in its total: it is two chunks in flight per thread, each holding a ~1MB input and a ~1MB output buffer - roughly 4MB per thread - not "2 buffers of ~4MB". An operator sizing heap should not have to re-derive it. - Removed the second check of the carried failure in backupDatabase(). writeArchive rethrows it from inside its own callback, which it must do so the stream-closing there knows the backup failed, so the outer check was unreachable - and an unreachable safety net only suggests to the next reader that the throw above might not happen.
|
This one crossed with my previous reply too - answering the 22:37 review separately. All three nits were right, all three fixed. 3 (taking it first, it is the one that mattered). The 1. Peak-heap prose. Wrong in its parts while right in its total, which is the worst kind of doc error because the total looks like it confirms the breakdown. It is two chunks in flight per thread, each holding a ~1MB input and a ~1MB output buffer - roughly 4MB per thread, ~32MB at 8 threads - not "2 buffers of ~4MB each". Reworded so an operator sizing heap does not have to re-derive it. 2. Redundant Pushed as f77e7d8. |
ReviewI read through the full diff (engine + integration changes, Correctness
Concurrency
Minor / nit-level observations (none blocking)
Test coverageComprehensive: format-level round trips across the thread × level matrix, chunk-boundary sizes, ratio-cost bound, byte-identical restore output regardless of thread count, byte-for-byte comparison against the legacy writer, No dependency changes, so no Nice work - this is a substantial, carefully verified performance improvement with real defect fixes bundled in, and the test suite gives me confidence in the format-compatibility claims without having to trust the prose. |
…d one Ninth review round. The docs said ~32MB at 8 threads while the benchmark table in the PR reports 45.3MB, which reads as a contradiction to anyone cross-referencing them. Both are right and they measure different things: ~32MB is the compressor's own buffers, 45MB is the process heap, the same ~32MB on top of the ~12MB baseline the legacy single-threaded runs also show. Said so, in all three places that quote a number. The other two notes are deliberate and stay as they are: the one native Deflater the legacy writer's abort() leaves for its Cleaner (java.util.zip offers no way to release it without finishing the archive, which is exactly what must not happen on a failed backup), and the structural similarity between the two modules' int parsing, which cannot be shared across the engine/integration boundary and needs different exception types on each side anyway.
|
Review This is an exceptionally well-engineered PR - the commit history shows the author already ran about 9 self-review rounds covering ZIP64 edge cases, JDK-reference-byte comparisons, Info-ZIP interop, throttler overflow arithmetic, and abort-path resource cleanup, all backed by extensive tests (ParallelZipArchiveWriterTest, BackupCompressionIT, BackupSettingsTest). I read through the hand-rolled ParallelZipArchiveWriter (streaming ZIP64 container, SYNC_FLUSH chunk concatenation), the IoThrottler deadline arithmetic, the FullBackupFormat abort/failure-propagation rework, and the two real defects fixed along the way (Expression.toString() swallowing WITH ... settings, and the swallowed mid-backup failure). No correctness bugs found in that core logic - the reasoning about buffer pooling, thread confinement, executor queue sizing (maxChunksInFlight = threads*2 staying within the threads + queueCapacity bound so CallerRunsPolicy never fires), and the per-field ZIP64 sentinel promotion all checks out against the ZIP spec and ZipOutputStreams own behavior. Nit: leftover duplicated paragraph in the release notes docs/release-26.9.1.md lines 760-767 state the parallel-writer peak-heap figure twice back to back, with slightly different wording and numbers: "...Peak heap for the parallel path is bounded by construction at two chunks in flight per thread, each holding a ~1 MB input and a ~1 MB output buffer: ~32 MB of buffers at 8 threads, which is the ~45 MB the benchmark measures minus the ~12 MB baseline the process uses anyway. Scaling is close to linear: ... - 27x end to end. Peak heap for the parallel path is bounded by construction at two chunk buffers per thread, measured at 33 MB above baseline on 8 threads." This looks like a leftover from the "reconcile the documented heap figure" commit that added the corrected explanation without removing the original sentence it superseded. Minor (docs only), but worth trimming the second occurrence (and reconciling 32 MB vs 33 MB) before merge, since it reads as self-contradictory next to the benchmark table in the PR description. Everything else
Nice work overall - just the docs nit above worth cleaning up before merge. |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## main #6080 +/- ##
==========================================
+ Coverage 69.46% 69.50% +0.03%
==========================================
Files 1809 1813 +4
Lines 154818 155184 +366
Branches 32730 32780 +50
==========================================
+ Hits 107552 107854 +302
- Misses 33726 33769 +43
- Partials 13540 13561 +21 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
…settings when re-rendered to text (#6434) ExportDatabaseStatement#toString() and BackupDatabaseStatement#toString() only rendered url, never settings, so re-serializing a parsed statement (statement caching keyed on text, query logging, an audit trail) silently lost the WITH clause. Widening the fix to the rest of the WITH-settings statement family found RebuildIndexStatement had the same gap in toString(), plus two related ones copy() never carried settings over at all (the same silent-drop shape #6080/#6409 fixed for Export/Backup/Import), and equals()/hashCode() never compared them, so two rebuilds with different settings compared equal. Introduced Statement#appendWithSettings() as the one shared renderer for the WITH clause and pointed all five settings-bearing statements at it (REBUILD INDEX, REBUILD TYPE, IMPORT/EXPORT/BACKUP DATABASE), replacing four copies of the same loop.
Fixes #6072 (phase 1 of
docs/optimize-backup.md). No archive-format change, no engine change to the write path, phases 2 and 3 untouched.What was slow
FullBackupFormatstreamed everyComponentFileinto a ZIP atsetLevel(9), on the calling thread. Deflate at level 9 sustains ~20-40 MB/s on one core, so the backup was CPU bound long before it was I/O bound.Duration is not the only cost. The backup runs inside
PageManager.suspendFlushAndExecute, and while flushing is suspended dirty pages pile up until they hitarcadedb.flushSuspendMaxDeferredRAM(512 MB), past which committing threads are throttled. The backup's duration is the writer-throttling window, so making the backup n times faster shortens the disruption by the same factor.What changed
arcadedb.backup.compressionLevel, default lowered from 9 to 1 on measurement (see below).arcadedb.backup.compressionThreads, default-1= half the available processors capped at 8;0selects the previous single-threadedjava.util.zip.ZipOutputStreamwriter, kept as an escape hatch. Splitting by archive entry would not have helped - a database is often a handful of very large files, sometimes one dominant one - so the split is inside each entry: the reader cuts every file into 1 MB chunks, each is deflated by its ownDeflaterand terminated withSYNC_FLUSH, and the compressed chunks are concatenated back in order. Deflate streams ended that way concatenate into one valid stream; this is the construction pigz uses for parallel gzip. Peak heap is bounded by construction at two chunk buffers per thread.arcadedb.backup.maxMBPerSecond, default 0 = unlimited: optional cap on the rate the backup reads the database files, so it cannot saturate the production disk. Applied to the read side deliberately - that is the I/O competing with the live workload.All three are also settable per backup: CLI (
-compressionLevel,-compressionThreads,-maxMBPerSecond), theBackupAPI, andBACKUP DATABASE ... WITH compressionLevel = 6, compressionThreads = 4.No new dependency. Zstd was considered and rejected: level-1 deflate plus parallelism closes the gap, and
zstd-jniis a native dependency.ZipOutputStreamcannot be handed pre-compressed data, so the parallel path emits the ZIP container itself (ParallelZipArchiveWriter, ~250 lines) using the streaming form the spec provides for unknown sizes - general-purpose bit 3, zeroed sizes in the local header, a data descriptor after the data - which is exactly whatZipOutputStreamemits for aDEFLATEDentry of unknown size, ZIP64 included.Benchmarks
BackupCompressionBenchmark(@Tag("benchmark"),**/*Benchmark.java, so it is in the benchmark lane only). Apple M-series, 10 cores, 1.25 GB database of ~2.1M indexed vertices with half-structured 512-byte payloads.Duration, archive size, heap
The trade, stated explicitly: 27x faster, 7.5% larger. The level change alone is 3.1x faster for 7.5% larger; the parallelism is free of ratio cost (347.66 MB single-chunk against 347.59 MB chunked - the empty-dictionary-per-chunk penalty is below the noise at 1 MB chunks, and is asserted by a test).
Scaling with thread count is near-linear (3.91x / 7.64x / 14.97x / 27.64x at 1 / 2 / 4 / 8), and total CPU is flat at ~5.2 cpu-seconds regardless, so the extra threads buy wall-clock without buying work. That is what the auto default of half-the-cores-capped-at-8 is chosen against: linear scaling means more threads is always faster, but a backup should not claim every core from the workload it is running alongside.
Impact on concurrent writers (the number that matters)
Sustained single-writer insert load, 200 records per transaction, measured only inside the backup window so a long backup and a short one are compared fairly:
The deferred-RAM high-water mark reaches the 512 MB
flushSuspendMaxDeferredRAMcap in every backed-up run, so writers were being throttled outright in all three - what changed is for how long, and how hard. In terms of write work displaced by one backup: ~7.4M records under the old default, ~76k under the new one, a ~97x reduction. Commit latency inside the window is barely affected either way; throughput, not latency, is where the suspension is paid for.Restore
Unchanged code path. Timed both ends of the trade on the same database: 2.9 s from a parallel level-1 archive. No regression - inflate is level-independent and the larger archive costs nothing measurable.
Two defects found on the way
BACKUP DATABASE ... WITH ...silently dropped every setting. The statement matched the setting name againstExpression.toString(), which renders a string quoted, so nocaseever matched. The visible consequence:WITH encryptionKey = '...'produced an archive in clear - it restored without the key. The same statement'scopy()also dropped the settings map, so a copy taken from the statement cache lost them again. Both fixed; the regression test asserts the archive is genuinely encrypted by requiring a keyless restore to fail. (ExportDatabaseStatementalready read the raw value correctly; this looks like a miss in the ANTLR parser migration.)A backup that failed halfway still reported success.
suspendFlushAndExecuteruns its callback throughCodeUtils.executeIgnoringExceptions, which logs and swallows, so an I/O error mid-backup left the archive to be finalized with a valid central directory over a truncated set of entries - a backup that looks valid and is not. The failure is now carried out of the suspension by hand and the partial archive is deleted.Verification
ParallelZipArchiveWriterTest(23 tests): every archive is read back twice, once withZipInputStream(what restore uses, never touches the central directory) and once withZipFile(what unzip uses, only the central directory), across the thread x level matrix, every chunk-boundary size (0, 1, n-1, n, n+1, 2n, 2n+1, ...), compressible / incompressible / all-zero / empty inputs; byte-for-byte equality between the parallel and the legacy writer's output; reported sizes matched against whatZipFilereads back; the throttle; and a 4 GB entry exercising the ZIP64 data descriptor and extra field, left in the normal lane rather than tagged slow because the slow lane only covers the engine module.BackupCompressionIT(16 tests): backup/restore round trips compared withDatabaseComparatoracross the thread x level matrix including the legacy writer, encrypted and plain; parallel and legacy archives restoring to identical databases; the SQL settings surface;GlobalConfigurationdefaults; and a backup taken under concurrent write load restoring to a whole number of committed batches.BackupSettingsTest: CLI parsing and range rejection.FullBackupIT,BackupDatabaseTest,Issue5517BloomFilterBackupIT, the wholeintegrationmodule, theserverbackup tests, and the engine configuration /PageManagerFlushSuspend/BackupDatabaseStatementtests.Concurrency
Per the
engine-concurrencyskill,ForkJoinPool.commonPool()is not used. The pool is a dedicatedThreadPoolExecutorwhose lifetime is exactly one backup - a backup is a rare, bursty operation, so a permanently resident pool would hold idle threads for the 99.99% of the time no backup runs, and there is no steady-state pool forPoolMetricsto report. Saturation is handled by construction rather than by a rejection policy: the reader keeps at mostthreads * 2chunks in flight, which bounds peak heap and back-pressures the reader, so the queue cannot fill and the caller-runs policy installed as a backstop never has to fire.