Skip to content

feat(#6072): faster full backup - configurable compression level and parallel compression - #6080

Merged
lvca merged 11 commits into
mainfrom
worktree-issue-6072-backup-phase1
Aug 11, 2026
Merged

lvca merged 11 commits into
mainfrom
worktree-issue-6072-backup-phase1

Conversation

@lvca

@lvca lvca commented Aug 11, 2026 •

Copy link
Copy Markdown
Member

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

FullBackupFormat streamed every ComponentFile into a ZIP at setLevel(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 hit arcadedb.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; 0 selects the previous single-threaded java.util.zip.ZipOutputStream writer, 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 own Deflater and terminated with SYNC_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), the Backup API, and BACKUP DATABASE ... WITH compressionLevel = 6, compressionThreads = 4.

No new dependency. Zstd was considered and rejected: level-1 deflate plus parallelism closes the gap, and zstd-jni is a native dependency. ZipOutputStream cannot 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 what ZipOutputStream emits for a DEFLATED entry 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

configuration seconds MB/s archive ratio vs base peak heap
legacy writer, level 9 (previous default) 18.88 67.9 323.46 MB 25.2% 1.00x 12.3 MB
legacy writer, level 6 10.71 119.6 321.66 MB 25.1% 1.76x 12.3 MB
legacy writer, level 1 6.18 207.5 347.66 MB 27.1% 3.06x 12.3 MB
parallel, level 1, 1 thread 4.82 265.6 347.59 MB 27.1% 3.91x 12.3 MB
parallel, level 1, 2 threads 2.47 518.5 347.59 MB 27.1% 7.64x 12.3 MB
parallel, level 1, 4 threads 1.26 1016.0 347.59 MB 27.1% 14.97x 31.3 MB
parallel, level 1, 8 threads 0.68 1875.8 347.59 MB 27.1% 27.64x 45.3 MB
parallel, level 6, 8 threads 1.39 924.3 321.78 MB 25.1% 13.62x 35.4 MB
parallel, level 9, 8 threads 2.96 432.2 323.56 MB 25.3% 6.37x 43.3 MB

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:

window throughput in window p50 p95 p99 peak deferred RAM
no backup running 10.0 s 159,560 rec/s 1,167 us 1,627 us 3,393 us 0
legacy writer, level 9 48.6 s 6,809 rec/s (4.3%) 1,619 us 2,098 us 2,302 us 512 MB (cap hit)
parallel, level 9, 8 threads 7.1 s 51,867 rec/s (33%) 1,647 us 2,297 us 2,486 us 512 MB (cap hit)
parallel, level 1, auto 2.1 s 123,192 rec/s (77%) 1,573 us 1,952 us 2,123 us 512 MB (cap hit)

The deferred-RAM high-water mark reaches the 512 MB flushSuspendMaxDeferredRAM cap 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 against Expression.toString(), which renders a string quoted, so no case ever matched. The visible consequence: WITH encryptionKey = '...' produced an archive in clear - it restored without the key. The same statement's copy() 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. (ExportDatabaseStatement already read the raw value correctly; this looks like a miss in the ANTLR parser migration.)

A backup that failed halfway still reported success. suspendFlushAndExecute runs its callback through CodeUtils.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 with ZipInputStream (what restore uses, never touches the central directory) and once with ZipFile (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 what ZipFile reads 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 with DatabaseComparator across the thread x level matrix including the legacy writer, encrypted and plain; parallel and legacy archives restoring to identical databases; the SQL settings surface; GlobalConfiguration defaults; and a backup taken under concurrent write load restoring to a whole number of committed batches.
  • BackupSettingsTest: CLI parsing and range rejection.
  • Existing suites green: FullBackupIT, BackupDatabaseTest, Issue5517BloomFilterBackupIT, the whole integration module, the server backup tests, and the engine configuration / PageManagerFlushSuspend / BackupDatabaseStatement tests.

Concurrency

Per the engine-concurrency skill, ForkJoinPool.commonPool() is not used. The pool is a dedicated ThreadPoolExecutor whose 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 for PoolMetrics to report. Saturation is handled by construction rather than by a rejection policy: the reader keeps at most threads * 2 chunks 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.

…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.
@mergify

mergify Bot commented Aug 11, 2026

Copy link
Copy Markdown
Contributor

Tick the box to add this pull request to the merge queue (same as @mergifyio queue).

  • Queue this pull request

@lvca lvca self-assigned this Aug 11, 2026
@lvca lvca added this to the 26.9.1 milestone Aug 11, 2026
@codacy-production

codacy-production Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 105 complexity

Metric Results
Complexity 105

View in Codacy

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 Aug 11, 2026

Copy link
Copy Markdown

Review

Went through the full diff (engine GlobalConfiguration/PageManager/BackupDatabaseStatement, the new integration/backup writers, and all four new test classes). Overall this is a well-scoped, well-tested change — I traced through the ZIP container construction by hand (local header / data descriptor / central directory / ZIP64 extra field) and it matches APPNOTE.TXT, and it lines up with how java.util.zip.ZipInputStream actually decides 4- vs 8-byte data-descriptor fields (from the inflater's observed byte counts, not from a zip64 marker in the local header) — so the "no zip64 extra field in the local header" design is correct, not just untested luck. The entryLargerThan4GBUsesZip64 test exercises exactly that path.

Correctness

  • BackupDatabaseStatement fix is real and correctly scoped. entry.getKey().toString() renders a quoted string ('compressionLevel'), so the old switch never matched anything — confirmed by reading Expression/SimpleNode, where .value is the raw unquoted field, same as ExportDatabaseStatement already reads it. Good catch, and the regression test (sqlEncryptionKeyIsActuallyApplied) asserting a keyless restore fails is the right way to prove the encryption bug is actually fixed rather than just "setting is applied".
  • The partial-archive-on-failure fix works but has a small internal wrinkle worth knowing about: PageManager.suspendFlushAndExecute's callback exception is swallowed internally, so by the time writeArchive's try-with-resources exits, callback.backup(archive) has already returned normally — meaning archive.close() (writing a real, valid-but-truncated central directory) still runs before FullBackupFormat notices failure.get() != null and deletes the file. End behavior is correct (caller gets an exception, file is deleted), but if close() itself throws in that same failure window (e.g. disk full while flushing the central directory), that secondary exception would replace the original root cause in the propagated failure. Very much an edge case (double-fault during an already-failing backup) and not worth blocking on, but flagging in case it ever shows up as a confusing error message in the field.
  • Deflate-stream concatenation (SYNC_FLUSH per chunk + one FINAL_EMPTY_BLOCK at the end) is bit-for-bit correct for the pigz-style trick, and the DOS-time bit packing in toDosTime is correct including the sign-extension-then-mask handling for post-2107 dates.
  • getDeferredRAMBytes() on PageManager correctly follows the existing volatile flushThread local-copy-then-null-check pattern used elsewhere in the class.

Concurrency (per the engine-concurrency skill)

No ForkJoinPool.commonPool() use; the per-backup ThreadPoolExecutor is sized so the reader's own backpressure (threads * 2 chunks in flight) always stays under the executor's total capacity (threads core + threads * 2 queue), so CallerRunsPolicy is genuinely a backstop, not the real mechanism, matching the class Javadoc's claim. inputBufferPool/outputBufferPool are plain ArrayDeque (correct — only ever touched by the single reader thread) while deflaterPool is a ConcurrentLinkedQueue (correct — touched by worker threads). This distinction is exactly right and easy to get wrong.

Test coverage

Strong. ParallelZipArchiveWriterTest covers chunk-boundary sizes, thread-count-independence of output bytes, byte-for-byte parity against the legacy writer, the 4 GB/ZIP64 path, and the throttle. BackupCompressionIT covers the SQL surface, the two real defects (encryption-dropped, settings-copy-dropped), and a concurrent-write-load backup verified via a "count is a whole number of 100-record batches" invariant, which is a nice cheap way to catch a torn read without a full byte comparison. BackupSettingsTest covers CLI parsing and range validation.

Minor/non-blocking notes

  • IoThrottler.throttle uses double division to compute the absolute deadline (totalBytes / (double) bytesPerSecond * ONE_SECOND_NANOS) — fine at backup scale (well within double's precision for realistic total bytes/rates), just flagging that it's not exact integer arithmetic in case someone later reuses this class somewhere precision-sensitive.
  • The PR description says the archive is "readable by any standard unzip tool, including the ZIP64 extensions an entry above 4 GB needs." That's verified for both of the JDK's own readers (ZipInputStream and ZipFile, both tested), which is what actually matters for the restore path. Third-party tools (e.g. Info-ZIP unzip extracting rather than just listing) weren't tested and could in principle handle the streaming ZIP64 data-descriptor case differently — low-risk edge case given it only applies to single files ≥4 GB, but worth knowing the claim's evidence is JDK-shaped.
  • Nice touch keeping arcadedb.backup.compressionThreads = 0 as a documented escape hatch back to the old, battle-tested single-threaded writer rather than deleting it outright.

No blocking issues found. This is ready modulo whatever the maintainers want to do with the double-fault edge case above.

…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.
@lvca

lvca commented Aug 11, 2026

Copy link
Copy Markdown
Member Author

Thanks - all three notes addressed.

1. Double-fault during an already-failing backup. Fixed properly rather than papered over. BackupArchiveWriter gains abort() (release the resources, do not terminate the archive), and writeArchive no longer uses try-with-resources: only a backup that actually succeeded is close()d, anything else aborts. Two consequences beyond the flagged one - a close() failure can no longer replace the root cause, and a failed backup never gets a valid central directory written at all, so even if the delete of the partial file cannot happen (permissions, full or read-only filesystem) what is left is structurally invalid rather than a plausible-looking archive missing files. Covered by abortLeavesNoValidArchive (both writers, asserts ZipFile rejects the result) and aFailedBackupThrowsAndLeavesNoArchive (makes a component file unreadable mid-backup, POSIX-guarded with assumeTrue).

2. IoThrottler double division. Now exact integer arithmetic. The overflow that motivated the double (totalBytes * 1e9 exceeds a long past ~9.2 GB, which a backup does reach) is handled by re-baselining every GB, and because the new baseline is the previously computed deadline rather than now, no rounding drift accumulates.

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):

$ unzip -t zip64.zip            # Info-ZIP 6.00 - inflates and CRC-checks, not just lists
    testing: huge.bin                 OK
    testing: small-b.bin              OK
No errors detected in compressed data of zip64.zip.

$ unzip -l zip64.zip
4294971392  08-11-2026 17:49   huge.bin

$ python3 -c "import zipfile; z=zipfile.ZipFile('zip64.zip'); print(z.testzip())"
None

So four independent readers now: ZipInputStream, ZipFile, Info-ZIP and Python zipfile. I did not turn this into a test - shelling out to unzip would make the suite depend on what is installed on the runner - but recorded it in ParallelZipArchiveWriter's Javadoc so the evidence lives in the source rather than only in this thread.

Pushed as 8a75001.

@claude

claude Bot commented Aug 11, 2026

Copy link
Copy Markdown

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 ZipInputStream, ZipFile, Info-ZIP unzip -t, and Python's zipfile). Two real bugs found along the way (WITH ... settings silently dropped via the Expression.toString() mismatch, and a failed backup reporting success) are fixed and each has a regression test. Test coverage is unusually thorough for a hand-rolled binary format: chunk-boundary sizes, ZIP64 (>4GB entry), abort-leaves-no-valid-archive, concurrent-write-during-backup consistency, and byte-identical output across thread counts.

Code quality / correctness

  • ParallelZipArchiveWriter correctly preserves entry order despite out-of-order task completion: drainChunk calls future.get() on inFlight.poll() in FIFO submission order, so writes land in order even though the executor processes chunks concurrently. Buffer pools (inputBufferPool/outputBufferPool, plain ArrayDeque) are only touched from the single calling thread; only deflaterPool (touched by worker threads) is a ConcurrentLinkedQueue. This is correct and worth calling out because it is easy to get backwards.
  • FullBackupFormat.writeArchive's failure propagation is subtle but correct: suspendFlushAndExecute swallows exceptions internally (CodeUtils.executeIgnoringExceptions), so the code carries the failure out by hand via AtomicReference<Exception> and checks it before deciding archive.close() vs archive.abort(). Traced through both the exception-swallowed-inside-suspend path and the exception-thrown-directly-from-executeInReadLock path, and both correctly land on abort() plus delete.
  • Minor: GlobalConfiguration.BACKUP_COMPRESSION_LEVEL/BACKUP_COMPRESSION_THREADS/BACKUP_MAX_MB_PER_SECOND don't use the Callable validation hook that other entries in this enum use (e.g. PROFILE, DUMP_METRICS_EVERY). BackupSettings.checkIntSetting/parseIntSetting validate the CLI/API/SQL paths, but a value set directly via GlobalConfiguration.BACKUP_COMPRESSION_LEVEL.setValue(...) or a system property/config file bypasses that and reaches new Deflater(level, true) unvalidated. The JDK's Deflater constructor does throw IllegalArgumentException for an out-of-range level, so it is not a silent failure, but it is a less friendly error further from where the value was set - which is exactly the failure mode the docstring on parseIntSetting says it is avoiding. Worth adding the same validation via the Callable hook for consistency; low priority.
  • ZipStreamArchiveWriter.abort() intentionally leaves the Deflater for GC/Cleaner rather than finishing the stream (well documented, deliberate tradeoff) - fine as is. ParallelZipArchiveWriter.release() has a similar, much narrower window: shutdownNow() interrupts workers and then the pool is drained on the caller thread, but a worker mid-DeflateChunk.call() at that exact moment will still return its Deflater to the pool in its finally block after the drain loop already found the pool empty. Since JDK Deflater has a Cleaner-based safety net, this just defers reclamation rather than leaking permanently, and it is abort/failure-path only - not worth blocking on, just flagging since it is easy to miss in review.

Performance

  • Matches the CLAUDE.md performance mantra: reused primitive-array buffer pools instead of per-chunk allocation, a BufferedOutputStream sized to coalesce only the small header writes (large chunk writes bypass the buffer, correctly reasoned about in the comment), and the automatic thread count (half the cores, capped at 8) deliberately leaves room for the live workload rather than saturating the machine.
  • Correctly avoids ForkJoinPool.commonPool() per the engine-concurrency skill/CLAUDE.md - uses a dedicated, backup-scoped ThreadPoolExecutor with a bounded queue and CallerRunsPolicy as a backstop that the sizing math (maxChunksInFlight equals queue capacity) ensures never actually fires.
  • The benchmark numbers in the PR description (27x end-to-end at 8 threads, writer throughput 4.3% to 77% during the backup window) are a good example of measuring rather than assuming, and the benchmark class is correctly tagged @tag("benchmark") and excluded from normal CI per the repo convention.

Security

  • The encryption fix is the most important part of this PR from a security standpoint: WITH encryptionKey = '...' previously silently produced an unencrypted archive because the setting match was against Expression.toString() (which quotes strings) instead of Expression.value. The fix mirrors the existing pattern in ExportDatabaseStatement, and the regression test (sqlEncryptionKeyIsActuallyApplied) is the right shape - it proves encryption by asserting a restore without the key fails, not just that some bytes changed.
  • ParallelZipArchiveWriter.addFile uses inputFile.getName() (basename only) as the ZIP entry name, so there is no path-traversal (zip slip) surface introduced on the write side.

Test coverage

  • Very thorough, both at the integration level (BackupCompressionIT: round trips across thread/level combinations, encrypted round trip, parallel-vs-legacy byte-for-byte restore equivalence, SQL settings, concurrent-write-during-backup) and the format level (ParallelZipArchiveWriterTest: chunk-boundary sizes, ZIP64 >4GB entry via both a streaming and central-directory reader, abort leaves a structurally invalid archive, ratio cost of chunking stays bounded).
  • One thing to double check on CI: entryLargerThan4GBUsesZip64 is not tagged slow (explained in the test's own comment: the slow lane is engine-module only, per .github/workflows/mvn-test.yml). Worth confirming the integration module's regular test lane's timeout/disk budget in CI actually accommodates a >4GB sparse file comfortably, since assumeTrue only guards free disk space, not runtime.

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.
@lvca

lvca commented Aug 11, 2026

Copy link
Copy Markdown
Member Author

Second round addressed - all three points were valid, all three implemented.

1. GlobalConfiguration validation hook. Agreed, and the docstring on parseIntSetting was literally describing the gap it left open. Rather than the Callable hook I used the allowed-set mechanism already in the enum (integerRangeAsStrings, as SUPERNODE_STRIPES-style entries do) - worth noting the Callable hook could not have enforced this anyway: setValue catches a throwing callback and only logs SEVERE, so the value would still be accepted. The allowed check throws from inside the outer try, which restores the previous value and rethrows, which is the behaviour we want.

  • BACKUP_COMPRESSION_LEVEL → integerRangeAsStrings(0, 9)
  • BACKUP_COMPRESSION_THREADS → integerRangeAsStrings(-1, 256)
  • BACKUP_MAX_MB_PER_SECOND → deliberately none, now documented on the setting: the range is open-ended upwards so no set can express it, and it needs none because any non-positive value already means "throttle disabled" rather than "invalid".

The API/CLI upper bound moved from 1024 to a shared BackupSettings.MAX_COMPRESSION_THREADS = 256 so the four surfaces cannot drift apart. New test globalConfigurationRejectsOutOfRangeValues pins both the rejection and that a rejected value is not left behind.

2. release() racing a worker returning its Deflater. Fixed rather than left as deferred reclamation - release() now awaitTermination(10s) after shutdownNow(), so no worker can still be in DeflateChunk.call() when the pool is drained. Chunks are ≤1MB so termination is immediate; the timeout only exists so a pathological case degrades to the old behaviour instead of hanging.

3. 4GB test and the CI budget. Checked: ParallelZipArchiveWriterTest is *Test.java, so it runs in the unit-tests lane, not integration - timeout-minutes: 60 on the job, no per-test JUnit timeout configured anywhere. Disk is fine (sparse source, ~19MB archive, and assumeTrue requires 5GB free as insurance against a filesystem that materialises it). Runtime is ~2s here. But you are right that "the job cap is the only guard" is not a good answer for a test moving 4GB, so it now carries @Timeout(10, MINUTES) - two orders of magnitude of headroom, and it fails fast and legibly instead of eating the lane if that ever stops being true.

Pushed as 0aa9d83.

…ackup-phase1

# Conflicts:
#	docs/release-26.9.1.md
@claude

claude Bot commented Aug 11, 2026

Copy link
Copy Markdown

Review: Faster full backup (configurable compression level + parallel compression)

I read through the diff in full (GlobalConfiguration, PageManager, BackupDatabaseStatement, Backup, BackupSettings, IoThrottler, BackupArchiveWriter, FullBackupFormat, ParallelZipArchiveWriter, ZipStreamArchiveWriter, and all four new test classes) and compiled the merged tree locally. Overall this is exceptionally well engineered: the hand-rolled ZIP writer is careful about the streaming-data-descriptor + ZIP64 edge cases, the failure handling (abort()/central-directory-only-on-success) closes a real correctness hole, and the test suite is unusually thorough (byte-for-byte comparison against the legacy writer, chunk-boundary sizes, a real 4GB ZIP64 entry, throttling, concurrent-write consistency, and regression tests for both defects found along the way).

Correctness

  • ParallelZipArchiveWriter backpressure: I traced the inFlight/maxChunksInFlight bookkeeping in addFile carefully because the submit-then-check ordering looked suspicious at first (inFlight.add(submitChunk(...)) happens before the while (inFlight.size() >= maxChunksInFlight) drain). It works out correctly: the loop only ever lets inFlight grow to exactly maxChunksInFlight before draining back down, so the documented "threads*2 chunks in flight" / ~32MB-at-8-threads bound is accurate and the CallerRunsPolicy backstop genuinely never fires in the steady state. No bug here, just noting I checked it since it's the trickiest part of the class.
  • The close()-throws-mid-write case is handled correctly: FullBackupFormat.writeArchive's finally calls archive.abort() whenever close() didn't fully complete, and both ParallelZipArchiveWriter.abort() and .close()'s own release() are idempotent (closed flag, deflaterPool.poll() no-ops when empty), so the double-release path introduced by that safety net is safe.
  • IoThrottler's rebasing (moving the baseline to the just-computed deadline every ~1GB rather than to now) correctly avoids both the long-overflow and rounding-drift issues called out in the commit message.
  • The SQL fix (Expression.toString() renders quoted, so no case ever matched) is a genuine, previously-silent security bug — WITH encryptionKey = '...' writing a cleartext archive. Good catch, and the regression test (sqlEncryptionKeyIsActuallyApplied) proves it by asserting a keyless restore now fails.

Minor / nit

  • BackupCompressionBenchmark.java uses com.sun.management.OperatingSystemMXBean inline as a fully-qualified name (processCpuNanos()) instead of importing it, which goes against this repo's CLAUDE.md guidance ("don't use fully qualified names if possible, always import the class"). It's a @Tag("benchmark") test file excluded from normal CI, so low priority.
  • parseIntSetting/range-checking logic is duplicated between BackupDatabaseStatement (engine module) and BackupSettings (integration module). Looks unavoidable given the module boundary (engine can't depend on integration), just flagging for awareness rather than as something to change.
  • Not introduced by this PR, but worth knowing: BACKUP DATABASE ... WITH ... still silently ignores an unrecognized setting name (no default throwing in the switch). Pre-existing behavior, orthogonal to the fix here.

Performance & concurrency

  • Follows the engine-concurrency skill correctly: dedicated per-backup ThreadPoolExecutor, no ForkJoinPool.commonPool() usage, daemon threads, bounded queue with CallerRunsPolicy as a backstop rather than the primary mechanism.
  • The chunked-SYNC_FLUSH concatenation approach (pigz-style) is sound and the empty-dictionary-per-chunk cost is measured and asserted (chunkingCostsLittleRatio), not just assumed.
  • Default auto-sizing (half the cores, capped at 8) deliberately leaves room for the live workload — reasonable default given the backup runs during a flush-suspension window that throttles writers.

Test coverage

Very strong: ParallelZipArchiveWriterTest verifies every archive through both a streaming reader (what restore uses) and a central-directory reader (what standard unzip tools use), covers all chunk-boundary sizes, empty/incompressible/all-zero inputs, and a genuine 4GB ZIP64 entry with an explicit timeout guard. BackupCompressionIT covers the full thread×level matrix, encryption, SQL settings, both defect regressions, and a concurrent-write-load consistency check. BackupSettingsTest covers CLI parsing and range rejection at every entry point (CLI, API, SQL, GlobalConfiguration.setValue).

No blocking issues found. Nice work.

@claude

claude Bot commented Aug 11, 2026

Copy link
Copy Markdown

Review

Went through the full diff, plus the accompanying test suites (ParallelZipArchiveWriterTest, BackupCompressionIT, BackupSettingsTest) and the hand-rolled ZIP writer's byte-level logic. Overall this is an unusually well-engineered and well-tested change: the streaming-data-descriptor + ZIP64 construction is correct as far as I traced it, the concatenated-SYNC_FLUSH deflate trick is sound (matches the pigz construction), and the buffer-pool/executor lifecycle in ParallelZipArchiveWriter has no obvious races (single-threaded reader owns the buffer pools, Future.get() provides the happens-before for the compressed chunks, deflaterPool is a ConcurrentLinkedQueue). The two pre-existing defects fixed on the way (the WITH ... settings being silently dropped due to matching on Expression.toString(), and a backup that failed mid-stream still reporting success) are real bugs and the fixes are correct - confirmed SimpleNode.value is a public Object field so reading entry.getKey().value directly is valid and not fragile.

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 (ParallelZipArchiveWriter.java, writeEndOfCentralDirectory)
When zip64 is true because the size/offset overflowed but the entry count did not (exactly the scenario the 4GB single-entry test exercises), the code writes Math.min(count, ZIP64_MAGICCOUNT) (i.e. the real, non-sentinel count) into the classic EOCD record instead of the conventional 0xFFFF sentinel that most zip64-aware readers use as a signal to "trust the zip64 record instead." APPNOTE.TXT's wording ("if a field is too small... SHOULD be set to -1") technically allows this per-field approach, and the PR states it's been verified against ZipInputStream, ZipFile, Info-Zip unzip -t and Python zipfile, so this is likely fine in practice - but it diverges from what ZipOutputStream/Info-Zip produce themselves (they typically set all four EOCD fields to sentinels together whenever zip64 is used at all). Worth an explicit test asserting a tool that keys off the sentinel-then-fallback-to-zip64 pattern still parses this, if not already covered.

2. Root-cause exception can still be shadowed in one path (FullBackupFormat.encryptFile)
The PR's second commit specifically fixed the case where the archive's own close() failing after a mid-backup failure would replace the root cause (abort() was added for this). But encryptFile's outer finally { archiveStream.close(); } still unconditionally closes the CipherOutputStream/FileOutputStream after callback.write(...) returns, including on the abort path, and if that close throws (e.g. a CipherOutputStream.close() -> doFinal() failure), it will propagate from encryptFile and supersede whatever failure.get() already captured in backupDatabase(), since the throw failure.get() after writeArchive(...) never gets reached. Probably rare in practice for the cipher modes in use here, but worth confirming it's an acceptable residual gap.

3. Default compression level change is a real behavior change for existing deployments
Lowering arcadedb.backup.compressionLevel from 9 to 1 by default means every upgrade silently produces ~7.5% larger backup archives unless an operator opts back into level 9 (or 6). This is clearly a deliberate, well-measured trade documented at length in the PR description and release notes, so no action needed here, just flagging it as the kind of default change worth double-checking is prominent enough for operators who are disk-space constrained on their backup targets.

4. Minor: abort() on ParallelZipArchiveWriter cancels in-flight futures without returning their buffers to the pool
In addFile's finally { for (pending : inFlight) pending.cancel(true); }, cancelled tasks never go through drainChunk, so their input/output buffers aren't pushed back to the pools. Since release() tears down the whole executor/deflater pool right after anyway, this is not a leak, just a very minor missed reuse on an already-failing path, not worth changing.

Test coverage: excellent. The chunk-boundary parameterization (0, 1, n-1, n, n+1, 2n, 2n+1, ...), dual-reader verification (ZipInputStream vs ZipFile), the byte-for-byte comparison against the legacy writer, the throttle test, the abort test, and the explicit 4GB ZIP64 test (correctly left untagged rather than @Tag("slow"), since the slow lane only builds -pl engine and would silently never run this integration-module test - good catch, documented right in the test) all show real care. BackupCompressionIT's round-trip matrix and the encryption regression test (asserting a keyless restore fails, proving the archive is genuinely encrypted) directly cover the two defects called out in the description.

Performance/concurrency: sizing the default thread pool at half the cores capped at 8, using a dedicated ThreadPoolExecutor (not ForkJoinPool.commonPool()) with a bounded queue and CallerRunsPolicy as backstop, and back-pressuring via maxChunksInFlight in the reader loop all line up with the engine-concurrency conventions this repo has established elsewhere.

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.
@lvca

lvca commented Aug 11, 2026

Copy link
Copy Markdown
Member Author

Third round - thanks. Two of the three acted on, one deliberately not.

Fully-qualified OperatingSystemMXBean. Fixed, java.lang.management.OperatingSystemMXBean is imported and only the HotSpot-specific subinterface stays qualified in the instanceof (there is no way to import both under one simple name). Fair catch on the CLAUDE.md rule even in a benchmark file.

Unrecognised WITH ... setting silently ignored. You scoped this out as pre-existing and orthogonal, and it is - but I have implemented it anyway, because it is the same failure mode this PR exists to fix, reached by a second route: WITH encryptionkey = ... (one wrong character) looks like a request for an encrypted archive and produces a cleartext one. The switch now has a default throwing a CommandExecutionException that names the supported settings.

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 sqlRejectsAnUnknownSetting. Say the word and I will drop it.

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 Backup) would add public API purely to share eight lines. Noted in the commit message so the next reader does not re-derive it.

One note on local verification: BackupRestoreDeleteApiIT.restoreAndDeleteBackup fails on my machine, but it fails identically with this PR reverted - another process on this box is holding port 2480 (HTTP Port 2480 not available), so the server under test never binds. Not related to this change; CI has its own port.

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.
@lvca

lvca commented Aug 11, 2026

Copy link
Copy Markdown
Member Author

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 ZipOutputStream and with ParallelZipArchiveWriter and dumping both tails:

jdk  EOCD: entriesDisk=1 entriesTotal=1 cdSize=0000004A cdOffset=FFFFFFFF
ours EOCD: entriesDisk=1 entriesTotal=1 cdSize=00000052 cdOffset=FFFFFFFF

So the premise is not right: ZipOutputStream does not set all four fields to sentinels when zip64 is in use - it sets each field to its sentinel only if that field individually overflows (writeEND computes xlen/xoff/count independently). Real count, real directory size, sentinel offset. That is byte-for-byte what this writer emits, so there is nothing to change.

But the underlying worry was right, for a different reason. The ZIP64 end-of-central-directory branch had no test at all. entryLargerThan4GBUsesZip64 does not reach it: a 4GB compressible entry produces a ~19MB archive, so the directory offset never overflows - it covers the zip64 data descriptor and the zip64 CEN extra field only. The branch that was untested is the one that fires in ordinary production use, since any database of a few tens of GB yields an archive past 4GB.

New test archiveLargerThan4GBMatchesTheJdkEndOfCentralDirectory closes that: it writes a >4GB archive with both writers and asserts the end records field by field against the JDK's own bytes, so the two cannot drift. It costs no disk - sparse source, level 0 so the 4GB passes through as stored blocks, and both archives go into a sink that keeps only the last 256 bytes. Runs in 2.7s.

2. encryptFile's close can still shadow the root cause. Correct, and a genuine gap in the previous fix. writeArchive now rethrows the carried failure from inside the callback, so encryptFile knows the backup failed and attaches a close failure as addSuppressed rather than letting it replace the cause. On the success path a close failure still propagates, since the last bytes may not have reached the disk - that one is the backup's failure.

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 (=9, still several times faster than before since the parallelism is independent of the level, or =6 for the same size at half the CPU).

4. Cancelled futures not returning buffers to the pool. Agreed, no change - release() tears the whole pool down immediately after, on an already-failing path.

Pushed as 4e7ba74.

@claude

claude Bot commented Aug 11, 2026

Copy link
Copy Markdown

Review

Went 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 ZipInputStream.readEnd() actually infers descriptor width (from Deflater/Inflater byte counts rather than the local header), the chunk-buffer pooling is correctly confined to the single writer thread (only deflaterPool is touched from worker threads, and it's a ConcurrentLinkedQueue), and the abort()/close() split correctly prevents a truncated archive from ever getting a valid central directory. The test suite (ParallelZipArchiveWriterTest, BackupCompressionIT) is unusually thorough, especially reading every archive back through both ZipInputStream and ZipFile, and the chunk-boundary sweep.

A few smaller points:

1. BACKUP_COMPRESSION_THREADS upper bound is a duplicated literal, not actually shared (engine/src/main/java/com/arcadedb/GlobalConfiguration.java)
GlobalConfiguration.java hardcodes integerRangeAsStrings(-1, 256), while BackupSettings.MAX_COMPRESSION_THREADS = 256 is the constant actually referenced by the CLI, the Backup API, and (indirectly, via reflection) the SQL path. The commit message for the second review round says "The thread bound is now a shared constant so the four surfaces cannot drift apart," but engine can't depend on integration, so the GlobalConfiguration copy is necessarily a separate literal. It's consistent today, but nothing enforces that it stays consistent if MAX_COMPRESSION_THREADS changes later. Worth a one-line comment on the GlobalConfiguration entry pointing at BackupSettings.MAX_COMPRESSION_THREADS so a future editor knows to update both.

2. archive.close() (central directory write) now happens outside the read lock / flush-suspension window
In the old code, zipFile.close() ran inside suspendFlushAndExecute. In the new FullBackupFormat.writeArchive, archive.close() runs after callback.backup(archive) returns, i.e. after executeInReadLock/suspendFlushAndExecute have already released. Functionally this looks safe (the central directory is built purely from the already-collected entries list, no live database access needed), and it's a nice extra win in the direction the whole PR is pushing (shorter suspension window). But it's a behavior change not called out in the PR description/benchmarks, so worth confirming it was intentional rather than an incidental side effect of the refactor.

3. Minor test gap: SQL path never exercises an out-of-range numeric setting
sqlRejectsANonNumericSetting covers compressionLevel = 'high' (caught by BackupDatabaseStatement.parseIntSetting), but there's no test for e.g. compressionLevel = 20 via SQL, which takes a different path: it parses fine, then fails inside Backup.setCompressionLevel → BackupSettings.checkIntSetting, gets wrapped as InvocationTargetException, and is unwrapped by the existing outer catch (InvocationTargetException e) in executeSimple. I traced it through and believe it works, but given this PR's whole theme is "validate at every entry point," a regression test closing that last gap would match the rest of the suite's rigor.

4. IoThrottler.throttle() uses a single LockSupport.parkNanos call
Spurious wakeups aren't looped on, so a throttled read can occasionally return slightly early. Since the deadline math is cumulative/absolute, this self-corrects on the next call and has no real impact on a rate limiter for backup I/O, just flagging it as an intentional-looking simplification in case it wasn't.

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 engine-concurrency skill (dedicated pool, bounded in-flight chunks, no ForkJoinPool.commonPool()).

@claude

claude Bot commented Aug 11, 2026

Copy link
Copy Markdown

Review

This is an unusually thorough PR — I read through ParallelZipArchiveWriter, FullBackupFormat, IoThrottler, ZipStreamArchiveWriter, BackupArchiveWriter, the GlobalConfiguration/PageManager/BackupDatabaseStatement/Backup/BackupSettings changes, and the test suites. Overall this is high-quality, well-verified work. Notes below are minor; I did not find correctness bugs in the core paths.

Code quality / design

  • Custom ZIP container writer (ParallelZipArchiveWriter) is a reasonable trade given ZipOutputStream can't accept pre-compressed data. I traced the local-header / data-descriptor / central-directory / ZIP64 field layout byte-by-byte against APPNOTE.TXT — the ordering and sizes are correct, and the streaming-descriptor + ZIP64 combination (the trickiest part) matches what ZipInputStream/ZipFile expect.
  • Good separation of concerns via BackupArchiveWriter interface with ZipStreamArchiveWriter kept as an explicit escape hatch (compressionThreads = 0).
  • Buffer pools (inputBufferPool/outputBufferPool) are ArrayDeque (non-thread-safe) but are only ever touched from the single writer thread — worker threads only see the Deflater pool, which correctly uses ConcurrentLinkedQueue. This is a subtle invariant worth a one-line comment near the field declarations for future maintainers, since it's easy to "fix" by mistake (e.g. someone touching a buffer from drainChunk in a future change without realizing pooling isn't reentrant-safe).
  • The two pre-existing defects fixed here (the Expression.toString() matching bug that silently dropped WITH encryptionKey=..., and the swallowed-exception-behind-a-valid-central-directory bug) are real, well-isolated, and each has a regression test that specifically proves the symptom (keyless restore must fail; a failed backup must leave no archive) rather than just re-testing the fix mechanically.

Potential issues / nitpicks

  • Central directory ZIP64 field granularity (ParallelZipArchiveWriter.writeCentralDirectoryEntry): the zip64 boolean is OR'd across compressed size, uncompressed size, and local header offset, so once any one of the three overflows, all three central-directory size/offset fields get the 0xFFFFFFFF sentinel and all three get written into the extra field — even if, e.g., only the offset actually overflowed (common case: a large archive with a small file appended near the end). This is spec-legal and internally consistent (readers must trust the extra field once the sentinel is set), just slightly less space-efficient than doing it per-field like writeEndOfCentralDirectory already does with Math.min(...). Not worth blocking on given it's exercised by the >4GB tests, but worth a one-line comment explaining it's a deliberate simplification, in case a future reader assumes it's a bug and "fixes" it into an inconsistency.
  • GlobalConfiguration.BACKUP_COMPRESSION_THREADS hardcodes the 256 upper bound rather than referencing BackupSettings.MAX_COMPRESSION_THREADS — understandable since engine can't depend on integration (same reasoning already called out for the duplicated int-parsing in the commit messages), but since a future change to MAX_COMPRESSION_THREADS won't get a compiler error on the engine side, it'd be worth a // keep in sync with BackupSettings.MAX_COMPRESSION_THREADS comment at both sites so the drift is at least discoverable by grep.
  • PageManager.getDeferredRAMBytes() is a new public API surface whose only caller in this PR is the benchmark test. That's a fine metric to expose (useful for ops/monitoring too), just flagging that it's public API added primarily for test instrumentation, in case that wasn't intentional.

Performance

  • The benchmarking here is unusually rigorous (thread × level matrix, concurrent-writer-throughput impact measured inside the backup window specifically, peak heap tracked). The "backup duration = writer throttling window" framing and the choice to default to level 1 + auto-parallelism is well justified by the numbers in the PR description.
  • Bounding in-flight chunks to threads * 2 for backpressure instead of relying on CallerRunsPolicy as the primary mechanism is the right call — keeps peak heap bounded and avoids relying on rejection-based backpressure as anything but a backstop.
  • IoThrottler's absolute-deadline design (vs. token bucket) avoids drift, and the periodic re-basing at 1GB to keep totalBytes * 1e9 inside long range is correct (max totalBytes at rebase is 1<<30, so 1<<30 * 1e9 ≈ 1.07e18, comfortably under Long.MAX_VALUE).

Security

  • The encryption-related fixes (settings actually being applied, unknown setting names now erroring instead of silently producing a cleartext archive) are good security-hygiene fixes — the WITH encryptionkey = '...' typo case in particular was a real footgun since it looked like it worked. No new dependency was introduced, consistent with the Apache 2.0 / lightweight-dependency guidance.

Test coverage

  • Genuinely excellent: byte-boundary chunk sizes, thread × level matrix, dual-reader verification (ZipInputStream and ZipFile, matching how restore vs. generic unzip tools each read differently), a >4GB entry and a >4GB archive (two different ZIP64 trigger paths, both exercised), concurrent-writer-load backup, and SQL-surface settings validation including the two defect regression tests. The choice to leave the >4GB entry test untagged (rather than @Tag("slow")) because the slow lane's CI job only runs -pl engine is correct per .github/workflows/mvn-test.yml (slow-unit-tests job runs -pl engine only) — tagging it slow in the integration module would have made it silently never run anywhere. Good catch, and good that it's called out explicitly in the commit message.

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.
@lvca

lvca commented Aug 11, 2026

Copy link
Copy Markdown
Member Author

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:

CommandExecutionException: Error on backing up database
  caused by IllegalArgumentException: Backup setting 'compressionLevel' must be between 0 and 9, found 20

The reason is buried one level down, because the generic outer catch (InvocationTargetException) swallows it into a message that says nothing. On a PR whose theme is "validate at every entry point", validating and then reporting it uselessly is only half the job. The settings loop now catches InvocationTargetException itself and surfaces the setter's own message, so the top-level message is the actual reason. Test covers both compressionLevel = 20 and compressionThreads = -2.

1. Duplicated 256 bound. Correct - my earlier commit message overstated it as "a shared constant"; engine cannot reference BackupSettings, so the GlobalConfiguration copy is necessarily a separate literal. Both sides now carry a comment saying so, but a comment is not enforcement: backupThreadBoundMatchesTheGlobalConfiguration asserts that GlobalConfiguration accepts exactly MAX_COMPRESSION_THREADS and rejects + 1, so the build fails the moment they drift.

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: concurrentWriterImpact measures the window as the whole backupDatabase() call, so it still charges the central-directory write to the window even though it no longer suspends anything.

4. parkNanos not looped. It was a simplification rather than a decision, so I have made it exact: parkUntil loops against the absolute deadline, so a spurious wakeup cannot let a read through early. An interrupt breaks the loop and leaves the flag set for the reader thread, rather than being spun through - which is what a naive loop would have got wrong.

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.
@lvca

lvca commented Aug 11, 2026

Copy link
Copy Markdown
Member Author

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 ZipOutputStream.writeCEN does - and, decisively, this writer already did it per-field in the end-of-central-directory record, so the two halves of the same class disagreed with each other. Each field is now promoted on its own.

The entryLargerThan4GBUsesZip64 test now asserts the extra field is 8 bytes - one value, since only the uncompressed size overflows for a 4GB entry that compresses to a few MB at offset 0 - and that it is the same length java.util.zip produces for the same entry. Reference is the JDK, not my reading of the spec.

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 ArrayDeques are correct because only the addFile thread touches them, that the deflater pool is concurrent because workers do, and that the confinement is the invariant rather than the collection type.

GlobalConfiguration 256 bound. Already done in the previous push - comment at both sites, plus backupThreadBoundMatchesTheGlobalConfiguration, which asserts GlobalConfiguration accepts exactly MAX_COMPRESSION_THREADS and rejects + 1. A grep-discoverable comment was the suggestion; the test makes it a build failure instead.

PageManager.getDeferredRAMBytes() as public API. Intentional. The issue requires reporting the deferred-RAM high-water mark - the direct signal that writers were throttled - and no accessor existed. You are right that its only caller here is the benchmark; it is deliberately shaped as an ops-facing metric rather than a test hook, and it is the natural thing to wire into the metrics endpoint when the Phase 2 work touches the suspension itself. I have left that wiring out of this PR to keep it to phase 1.

Pushed as b22a9cc.

@codacy-production

codacy-production Bot commented Aug 11, 2026 •

Copy link
Copy Markdown

Up to standards ✅

🟢 Issues 0 issues

Results:
0 new issues

View in Codacy

🟢 Metrics 115 complexity

Metric Results
Complexity 115

View in Codacy

🟢 Coverage 92.21% diff coverage · -6.56% coverage variation

Metric Results
Coverage variation ✅ -6.56% coverage variation
Diff coverage ✅ 92.21% diff coverage

View coverage diff in Codacy

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.

@claude

claude Bot commented Aug 11, 2026

Copy link
Copy Markdown

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

  • ParallelZipArchiveWriter in-flight bound: maxChunksInFlight = threads * 2, and the executors ArrayBlockingQueue capacity is exactly maxChunksInFlight. Traced the submit/drain loop in addFile - a new chunk is always submitted while inFlight.size() <= maxChunksInFlight - 1 (the drain loop at the end of the previous iteration guarantees this), so the queue never actually overflows into CallerRunsPolicy under normal operation. Backpressure works as documented.
  • The abort path (ParallelZipArchiveWriter.release()) awaits pool termination before draining deflaterPool, correctly avoiding the race with a workers own finally { releaseDeflater(...) } called out in the "second review round" commit. Confirmed the logic holds.
  • FullBackupFormat.writeArchive: the not-try-with-resources + abort() on any non-terminated path is correct, and closing the central directory outside suspendFlushAndExecute/the read lock (since it is built purely from in-memory CentralEntry records) is a nice latency win that is easy to miss.
  • Verified PageManager.suspendFlushAndExecute really does swallow the callbacks exception via CodeUtils.executeIgnoringExceptions(..., true) - the "failed backup reports success" bug this PR fixes is real and the AtomicReference<Exception> failure fix is the right shape for it.
  • IoThrottler: the rebase-at-1GB logic keeps totalBytes * ONE_SECOND_NANOS inside a long and re-baselines from the previous deadline rather than "now", so there is no drift accumulation. The "fell more than 1s behind, forgo the excess credit" clause is the right call to bound catch-up bursts. Looks correct.

Minor / nitpick

  • ZIP64 local header version field: writeLocalFileHeader always writes VERSION_DEFLATE (20), never VERSION_ZIP64 (45), even for entries that end up needing ZIP64 in the data descriptor/central directory. The central directory entry correctly upgrades its version fields when zip64 is true, but the local header does not. In practice this is likely harmless (readers determine ZIP64-ness from the data descriptor via general-purpose bit 3 plus byte counts actually inflated, per the class Javadoc, and the PR states this was checked against ZipInputStream, ZipFile, Info-Zip unzip -t, and Pythons zipfile), but since this is called out as the trickiest combination a hand-written ZIP writer gets wrong, it might be worth a one-line comment explaining why the local header version does not need to change, or confirming against APPNOTE 4.4.3.2 explicitly.
  • The Info-Zip/Python verification is manual (per the PR description), not part of the automated suite - understandable since those tools are not guaranteed present on CI runners, but if there is a reasonably portable way to shell out to unzip -t conditionally (skip if not on PATH, similar to the POSIX-only permission test), it would make that verification durable instead of a one-time check.
  • resolveThreads()s auto-sizing formula (half the processors, capped at 8, min 1) in FullBackupFormat is private and only exercised indirectly (default-config round trip tests set explicit levels/threads). A small unit test asserting the formulas boundary values (1 core to 1 thread, 20 cores to 8 threads) would pin the behavior explicitly, though this is low risk given how simple the function is.
  • Duplication of parseIntSetting/range-checking between BackupDatabaseStatement (engine) and BackupSettings (integration) is called out and justified by the module boundary in the commit messages - agreed this is the right tradeoff, not worth plumbing a shared abstraction across modules for eight lines.

Performance

  • The core performance claims (deflate level 1 default, chunked parallel deflate via SYNC_FLUSH, half-cores-capped-at-8 default) are measured and documented with numbers, not asserted. The chunkingCostsLittleRatio test turning the "empty-dictionary-per-chunk" cost claim into an actual assertion (under 10% overhead) rather than leaving it as a comment is good practice.
  • Read-side throttle (IoThrottler) is deliberately on the read side rather than the write/compress side, which is the right call since that is the I/O actually contending with the live workload - documented well in both the Javadoc and GlobalConfiguration.
  • BufferedOutputStream wrapping in ParallelZipArchiveWriter only coalesces header fields (compressed chunks are at least the buffer size for typical chunk sizes and bypass it) - correctly reasoned in the inline comment.

Security

  • The two defects fixed here are real and worth calling out explicitly for anyone scanning history later: BACKUP DATABASE ... WITH encryptionKey = ... silently producing a cleartext archive (matching Expression.toString() instead of the raw value) is a serious bug fixed here, and it is backed by a regression test (sqlEncryptionKeyIsActuallyApplied) that specifically asserts a keyless restore fails - good, because a weaker test (just checking the archive differs) would not have caught it if encryption were silently downgraded rather than dropped entirely.
  • The unknown-setting-name rejection (WITH encryptionkey = ..., one wrong character) closing the same hole by a second route is a good defense-in-depth catch and is exactly the kind of fail-closed behavior you would want for security-relevant settings.
  • No new dependencies, so no new attribution/license surface to check.

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

  • docs/release-26.9.1.md and the GlobalConfiguration Javadocs are well-written but quite long/prose-heavy compared to neighboring entries in the same file - not a blocker, just noting the style difference for consistency if that matters to maintainers.

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.

@claude

claude Bot commented Aug 11, 2026

Copy link
Copy Markdown

Review

I read through the new/changed files in integration/.../backup (ParallelZipArchiveWriter, IoThrottler, BackupArchiveWriter, ZipStreamArchiveWriter, FullBackupFormat), BackupDatabaseStatement, GlobalConfiguration, Backup/BackupSettings, and the test suites. This is an unusually rigorous PR — the iterative review-round commits already caught and fixed the issues I'd normally flag (failure swallowed by suspendFlushAndExecute, settings bypassing validation via setValue(), per-field vs. all-fields ZIP64 promotion, the Expression.toString() matching bug). Overall this looks solid and ready modulo the notes below.

Correctness — hand-traced, no bugs found

  • The DOS date/time packing in ParallelZipArchiveWriter.toDosTime() (single 32-bit int, time in the low 16 bits / date in the high 16 bits) matches the byte order the ZIP local/central headers expect and the clamping for pre-1980/post-2107 timestamps is correct.
  • The concatenated-SYNC_FLUSH deflate construction, the FINAL_EMPTY_BLOCK / EMPTY_DEFLATE_STREAM byte constants, and the per-field (not all-or-nothing) ZIP64 promotion in writeCentralDirectoryEntry all check out against APPNOTE and match what ZipOutputStream.writeCEN does.
  • Buffer/deflater pool thread confinement: inputBufferPool/outputBufferPool are only touched by the single addFile caller thread, buffers aren't recycled until the corresponding Future is drained (i.e., after the worker's call() has returned), so there's no data race despite the plain ArrayDeque. The maxChunksInFlight = threads * 2 cap is consistent with the executor's bounded queue, so CallerRunsPolicy is genuinely a backstop as documented, not a hot path.
  • IoThrottler's absolute-deadline arithmetic, the 1GB rebase to avoid totalBytes * 1e9 overflow, and the "forget excess credit past 1s" catch-up logic all look correct, and parkUntil's loop against LockSupport.parkNanos's spurious-wakeup allowance is the right defensive pattern.
  • FullBackupFormat.writeArchive's failure AtomicReference correctly carries the exception out of suspendFlushAndExecute (which swallows via CodeUtils.executeIgnoringExceptions), and the abort-vs-close bookkeeping (terminated flag) matches the stated intent of never finalizing a central directory over a failed backup.
  • Verified the BACKUP DATABASE ... WITH ... fix end-to-end against SQLASTBuilder.visitBackupDatabaseStmt: keyExpr.value = key.getStringValue() stores the raw unquoted name, so entry.getKey().value in BackupDatabaseStatement now matches correctly — confirms the fix is complete, not just locally consistent.
  • ZIP64 correctness (the trickiest part of this PR) is backed by real coverage: entryLargerThan4GBUsesZip64 and archiveLargerThan4GBMatchesTheJdkEndOfCentralDirectory in ParallelZipArchiveWriterTest assert byte-for-byte against the JDK's own output for both the >4GB entry and >4GB archive cases, which is exactly the scenario a hand-rolled ZIP64 writer usually gets wrong silently.

Minor / non-blocking nits

  1. GlobalConfiguration.BACKUP_COMPRESSION_THREADS doc is slightly off on peak heap. It says "about 2 chunk buffers per thread (~4 MB each), so ~32 MB at 8 threads" — but maxChunksInFlight = threads * 2 means up to 2 chunks in flight per thread, each holding an input and output buffer (~1 MB each at the default DEFAULT_CHUNK_SIZE), i.e. ~4 buffers/thread of ~1 MB, not "2 buffers of ~4 MB". The ~32 MB total figure at 8 threads is right, just the per-buffer breakdown in the prose doesn't match the actual buffer size — worth a quick wording pass so an operator sizing heap doesn't extrapolate the wrong per-buffer size for a non-default chunk size.
  2. Redundant failure re-check in FullBackupFormat.backupDatabase(). writeArchive(...) already throws failure.get() internally (inside encryptFile's callback) whenever it's set, so the if (failure.get() != null) throw failure.get(); right after the call in backupDatabase() looks unreachable in practice. Harmless as defensive belt-and-suspenders, but if intentional, a one-line comment would save the next reader from wondering the same thing.
  3. BackupDatabaseStatement's rawKey != null ? rawKey.toString() : entry.getKey().toString() fallback re-introduces the exact Expression.toString() bug this PR fixes if rawKey (i.e. Expression.value) is ever null for a settings key. Given SQLASTBuilder always sets keyExpr.value to the identifier's string value, this path looks currently unreachable — but since it's silently falling back to the buggy behavior rather than failing loudly, consider either asserting rawKey != null or dropping the fallback so any future parser change that stops populating .value fails fast instead of quietly reintroducing the original defect.

Test coverage

Excellent — ParallelZipArchiveWriterTest (chunk-boundary sizes, both ZipInputStream and ZipFile readers, thread×level matrix, incompressible/empty/all-zero inputs, the >4GB entry and >4GB archive ZIP64 cases verified against the JDK's own bytes), BackupCompressionIT (round trips via DatabaseComparator, the encryption regression test, the unknown-setting-name regression test, concurrent-write-load backup), and BackupSettingsTest (CLI parsing/range rejection) look comprehensive. I didn't spot gaps worth calling out.

Performance / security

  • Matches the engine-concurrency skill guidance: dedicated bounded ThreadPoolExecutor per backup, not the common pool, daemon threads, bounded queue with backpressure from the reader rather than relying on the rejection policy.
  • Lowering the default compression level from 9→1 is called out clearly in the release notes as a behavior change (archive ~7.5% larger by default), with a documented escape hatch — good practice for a default change like this.
  • No new dependencies, encryption path (CipherOutputStream) is untouched by the parallel writer, and the two security-relevant defects found along the way (silently-dropped WITH settings producing a cleartext archive when encryption was requested, and a truncated-but-valid-looking archive on backup failure) are both fixed with regression tests that assert the security property (restore without key must fail), not just that the setter was called.

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.
@lvca

lvca commented Aug 11, 2026

Copy link
Copy Markdown
Member Author

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. ZipOutputStream.writeLOC has two branches, and for an entry with a data descriptor (general-purpose bit 3, which is every entry here) it writes version(e) = 20 and never reaches the branch that would write 45 - because with a data descriptor the sizes are not known when the local header is written, so there is nothing to base an upgrade on. The entryLargerThan4GBUsesZip64 test now reads the field out of both my archive and the JDK's for the same >4GB entry and asserts they agree at 20, so the reference is the JDK's bytes rather than either of our readings of APPNOTE.

Info-ZIP verification was manual. Now durable. archiveIsAcceptedByAnIndependentUnzipImplementation shells out to unzip -t (which inflates and CRC-checks, not just lists) when the binary is on PATH and skips otherwise, the same shape as the POSIX-only permission test. Worth doing precisely because ZipInputStream and ZipFile share one implementation of the format, so agreeing with both is weaker evidence than it looks - Info-ZIP is genuinely independent. It runs on the ordinary fixture rather than a multi-GB archive: the streaming data descriptor is the unusual part and every entry carries one, so a small archive exercises the interop risk without the runtime.

resolveThreads() boundaries. Extracted to a package-private autoCompressionThreads(int availableProcessors) so it can be pinned without depending on the core count of whatever runs the suite, and covered at 1/2/3/4/8/16/20/64/128 cores plus the degenerate 0 and -1. You called it low risk and it is - but the formula encodes a deliberate trade (leave half the machine to the workload the backup is already throttling; do not put 32 threads on a job that saturates the disk first) that a one-character edit could change with nothing else failing.

parseIntSetting duplication. Agreed, leaving it.

Nit on prose-heavy docs. Keeping it - the neighbouring entries in docs/release-26.9.1.md are the same shape, and for a hand-written binary format the "why" is the part that stops the next reader from breaking it. Happy to trim if maintainers prefer shorter.

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.
@lvca

lvca commented Aug 11, 2026

Copy link
Copy Markdown
Member Author

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 rawKey != null ? rawKey.toString() : entry.getKey().toString() fallback falls back to the buggy match this PR exists to remove. You are right that it is currently unreachable - SQLASTBuilder always sets keyExpr.value - but "unreachable today, and if it ever becomes reachable it silently writes cleartext archives again" is not a defensible shape for this particular line. It now throws a CommandExecutionException instead of falling back, with a comment saying why there is no fallback, so a future parser change that stopped populating value fails loudly rather than quietly reintroducing the defect.

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 failure.get() re-check. Correct, it is unreachable: writeArchive rethrows the carried failure from inside its own callback (it has to, so the stream-closing there knows the backup failed - that was the fix for an earlier round's finding). Rather than comment it as intentional I removed it, because an unreachable safety net mostly teaches the next reader that the throw above might not happen. Replaced with a comment explaining where the throw actually is.

Pushed as f77e7d8.

@claude

claude Bot commented Aug 11, 2026

Copy link
Copy Markdown

Review

I read through the full diff (engine + integration changes, ParallelZipArchiveWriter, IoThrottler, ZipStreamArchiveWriter, FullBackupFormat, BackupDatabaseStatement, GlobalConfiguration, PageManager, and all four test classes). Overall this is a very well-engineered change: correct ZIP64 handling verified against the JDK's own bytes, careful resource lifecycle on the abort path, and two real, well-documented bugs fixed along the way. I did not find any functional or compile issues. Notes below are mostly confirmations and minor nits.

Correctness

  • ParallelZipArchiveWriter's streaming ZIP layout (bit-3 data descriptor, per-entry and end-of-central-directory ZIP64 promotion) matches what ZipOutputStream emits for unknown-size DEFLATED entries, and this is asserted byte-for-byte against the JDK writer in ParallelZipArchiveWriterTest (including the >4GB entry and >4GB archive cases, each triggering a different ZIP64 branch). That's a strong way to pin a hand-rolled binary format.
  • The chunked-deflate-with-SYNC_FLUSH concatenation trick is sound and the "same construction pigz uses" framing is accurate; chunkingCostsLittleRatio and threadCountDoesNotChangeTheRestoredBytes are good tests to have caught a regression here.
  • IoThrottler's absolute-deadline limiter correctly avoids double-precision drift by rebasing every ~1GB (REBASE_BYTES) instead of letting totalBytes * 1e9 overflow a long, and the "forgive more than 1s of backlog" logic prevents a stalled disk from turning into an unbounded burst later. Good.
  • The two defects called out in the description are real and the fixes are correct:
    • BackupDatabaseStatement was matching Expression.toString() (which quotes strings) instead of the raw Expression.value — every WITH ... setting, including encryptionKey, was silently ignored. Now fixed, and sqlEncryptionKeyIsActuallyApplied proves it by asserting a keyless restore fails.
    • suspendFlushAndExecute swallowing exceptions via CodeUtils.executeIgnoringExceptions meant a mid-backup I/O failure could still produce a "successful" backup with a valid-looking but truncated central directory. The AtomicReference<Exception> failure + explicit archive.abort() on any non-terminated path closes that hole, and BackupArchiveWriter.abort() is implemented correctly on both writers (no-op-but-documented for the legacy ZipOutputStream, since the JDK gives no way to release its Deflater without finishing the archive).
  • resolveThreads() / autoCompressionThreads() boundary values (1, 2, 3, 4, 8, 16, 20, 64, 128 cores) are pinned by FullBackupFormatThreadSizingTest, which is exactly the kind of "trivial formula, still worth a test" case that silently regresses otherwise.
  • The BACKUP_COMPRESSION_THREADS upper bound (256) is duplicated between GlobalConfiguration (engine can't depend on integration) and BackupSettings.MAX_COMPRESSION_THREADS, and the duplication is guarded by backupThreadBoundMatchesTheGlobalConfiguration — good use of a test to keep a necessary duplication honest instead of just a comment.

Concurrency

  • Per engine-concurrency, the pool is a dedicated per-backup ThreadPoolExecutor, not ForkJoinPool.commonPool(), and it's sized/bounded appropriately (daemon threads, named, CallerRunsPolicy backstop that the design shows can't actually fire since in-flight chunks are capped at threads * 2 = queue capacity).
  • Buffer-pool thread confinement is documented in-line (inputBufferPool/outputBufferPool touched only by the single reader thread, deflaterPool is the only genuinely concurrent structure) — worth flagging that this is an invariant a future edit could easily violate silently; the comment calls that out explicitly, which is the right way to guard it.
  • release() correctly relies on awaitTermination returning only after in-flight workers' finally blocks (which return their Deflater) have run, before draining deflaterPool. No leak on the interrupt/abort path.

Minor / nit-level observations (none blocking)

  • Docs say "peak heap ... ~32MB at 8 threads" (GlobalConfiguration javadoc and the class javadoc on ParallelZipArchiveWriter), while the PR's own benchmark table measures 45.3MB at 8 threads / level 1. Not wrong (it's "about 2 buffers/thread" as a mental model, not a hard bound), but the two numbers will look inconsistent to a reader who cross-references them - might be worth aligning the doc estimate with the measured figure, or noting it's a lower bound rather than a peak.
  • ZipStreamArchiveWriter.abort() deliberately leaks one native Deflater per aborted legacy-writer backup (well documented, and backups are rare/bursty, so this is a reasonable trade - just flagging it as an intentional, not accidental, leak in case it's ever revisited).
  • BackupSettings.parseIntSetting / checkIntSetting and the SQL statement's own parseIntSetting in BackupDatabaseStatement are structurally identical (parse + range-check + a formatted IllegalArgumentException/CommandExecutionException). Not worth a shared helper given the different exception types each layer needs to throw, but flagging in case future settings want to consolidate.

Test coverage

Comprehensive: 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, EntryStats vs ZipFile's own numbers, throttle timing, abort-produces-no-valid-archive (both writers), ZIP64 on both the >4GB-entry and >4GB-archive axes (correctly gated with @Timeout and an assumeTrue disk-space check), an Info-ZIP unzip -t interop check, full backup/restore round trips via DatabaseComparator (plain and encrypted), the SQL WITH ... surface, and the two regression tests for the defects found along the way. The benchmark class is correctly @Tag("benchmark")-gated per the repo's CI-lane conventions, and the >4GB tests are deliberately left untagged with a documented rationale (the slow lane doesn't cover this module).

No dependency changes, so no ATTRIBUTIONS.md/NOTICE update needed, and that checks out against the diff.

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.
@claude

claude Bot commented Aug 11, 2026

Copy link
Copy Markdown

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

  • Design: no new dependency (zstd was explicitly considered and rejected, the right call given the license/native-dependency tradeoff in CLAUDE.md); a dedicated ThreadPoolExecutor per backup rather than ForkJoinPool.commonPool(), consistent with the engine-concurrency skill.
  • Security: the encryptionKey regression fix is a genuine, worthwhile find - a backup requested with encryption was silently written in clear. Good regression test (sqlEncryptionKeyIsActuallyApplied) that asserts a keyless restore fails, rather than just checking the setter was invoked.
  • Correctness: the abort-vs-close split in BackupArchiveWriter/FullBackupFormat.writeArchive correctly ensures a failed backup never gets a valid central directory, and the close-failure-vs-root-cause suppression logic in encryptFile is handled carefully.
  • Test coverage: thorough - thread x level matrix for round-trips, chunk-boundary sizes, ZIP64 (over 4GB) end-of-central-directory bytes asserted field-by-field against the JDKs own writer, Info-ZIP interop (skipped gracefully when the binary is not on PATH), a concurrent-write-load consistency check, and CLI/SQL/GlobalConfiguration validation surfaces all covered independently (plus a test enforcing the two MAX_COMPRESSION_THREADS bounds cannot drift apart).
  • Performance: the benchmark numbers in the PR description are convincing, and the auto-thread-sizing tradeoff (half the cores, capped at 8) is reasonable and pinned by FullBackupFormatThreadSizingTest.
  • No lingering System.out debug statements outside the @tag("benchmark") class, where printing is the intended behavior of a manual benchmark tool.

Nice work overall - just the docs nit above worth cleaning up before merge.

@codecov

codecov Bot commented Aug 11, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.93467% with 52 lines in your changes missing coverage. Please review.
✅ Project coverage is 69.50%. Comparing base (ec0fc4a) to head (028008d).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
...ration/backup/format/ParallelZipArchiveWriter.java 85.53% 20 Missing and 15 partials ⚠️
...a/com/arcadedb/integration/backup/IoThrottler.java 72.41% 5 Missing and 3 partials ⚠️
...db/integration/backup/format/FullBackupFormat.java 94.28% 2 Missing and 2 partials ⚠️
...src/main/java/com/arcadedb/engine/PageManager.java 0.00% 2 Missing ⚠️
...egration/backup/format/ZipStreamArchiveWriter.java 93.33% 2 Missing ⚠️
...om/arcadedb/integration/backup/BackupSettings.java 91.66% 0 Missing and 1 partial ⚠️
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.
📢 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 added a commit that referenced this pull request Aug 19, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Speed up full backup: configurable compression level and parallel compression (Phase 1 of backup optimization)

1 participant