diff --git a/seaweed-block/internal/docs/current-plan.md b/seaweed-block/internal/docs/current-plan.md index 0c3995f5cb..9629e18e48 100644 --- a/seaweed-block/internal/docs/current-plan.md +++ b/seaweed-block/internal/docs/current-plan.md @@ -1,321 +1,214 @@ -# Current Plan: Phase 171 Default WALStore Checkpoint Pipeline +# Current Plan: Phase 172 WAL Materialization Pipeline Status: active evidence-first shipped-backend milestone. -Phase 170 proved that WAL append-call coalescing is mechanically effective but -not sufficient under the complete default `walstore` workload: +## Why This Is Next + +Phase 171 rejected bounded contiguous extent writeback without weakening its +gate. Its instrumentation exposed a different stable amplification in the +default `walstore` flusher: ```text -ordinary writers=4 64.09 MiB/s -explicit batch writers=4 47.22 MiB/s -batch/ordinary 0.737x -ordinary WriteAt calls/entry 1.000 -batch WriteAt calls/entry 0.06250 -paired batch gains 2/5 -ordinary four-writer range 2.936x -batch four-writer range 3.500x +ordinary dirty entry: + ReadAt(header) = 1 operation + ReadAt(full record) = 1 operation + extent WriteAt = 1 operation + +Linux strace control: + workload = BenchmarkPhase167WALStoreContention/writers_4 + logical writes = 67,539 + pread64 = 155,282 calls + pwrite64 = 155,304 calls + fsync = 44 calls ``` -The batch control reduced WAL `WriteAt` calls by about 16x, yet throughput and -stability did not improve. A staged append owner was therefore rejected before -implementation. +The header is read once to discover and validate the record, then read again as +part of the full record. Product counters report one header read and one record +read per validated dirty entry across sequential and scattered workloads. This +is deterministic work, unlike the snapshot-dependent coalescing opportunity +that failed Phase 171 admission. -The next measured seam is the other half of the shipped persistence pipeline. -The default flusher snapshots the complete dirty map and, for each current -entry, reads and validates WAL location metadata, reads block data, issues one -extent `WriteAt`, fsyncs the shared file, persists the checkpoint, and advances -the recyclable tail. This work competes with foreground WAL append on the same -file and currently exposes only flush-count and byte-count evidence. +The next candidate therefore changes only WAL materialization: provide enough +trusted in-memory record geometry to issue one bounded read, then run the +existing decode, CRC, LSN, type, LBA, length, data-offset, wrap, and stale-slot +checks before using any bytes or advancing checkpoint. -The plan review also found correctness debt in this path that must be fixed -before optimization: - -- `persistCheckpoint` currently updates the in-memory checkpoint before its - superblock write succeeds, so a later cycle can incorrectly treat a failed - checkpoint as reusable; -- checkpoint metadata is not fsynced before in-memory WAL-tail reuse; -- `Close` marks the store closed before `flusher.Stop` requests its final - cycle, so that promised final flush currently exits without work; -- default `walstore` has no explicit extent-write ownership rule between - flusher writeback and direct rebuild BASE installation; -- a WAL-slot mismatch currently deletes the dirty entry and continues, even - though the flusher has not proved that entry was already durably - checkpointed. - -Phase 167 already proved that bounded contiguous checkpoint writes can reduce -writeback syscall amplification in the opt-in `parallel-walstore`. Phase 171 -tests the corresponding mechanism in the default `walstore`, without changing -its disk format, recovery rules, or public storage contract. +This is one large milestone. Record identity, single-read materialization, +shared-record reuse, corruption and concurrency behavior, Linux performance, +and conditional mounted admission are deliverables inside Phase 172. ## Goal -Build one evidence-gated checkpoint/writeback improvement for the shipped -`WALStore` that: +Build one disabled-by-default comparison path for the shipped `WALStore` that: -- first makes checkpoint publication, tail reuse, Close, and direct BASE - overlap failure-safe; -- measures foreground WAL and background checkpoint work independently; -- preserves the current complete-snapshot checkpoint invariant; -- materializes every verified latest dirty block before advancing checkpoint; -- combines contiguous extent LBAs into bounded positioned writes; -- retains compare-and-delete protection against concurrent overwrite; -- keeps circular-WAL validation, retention pins, Sync, recovery, direct BASE - install, and rebuild semantics unchanged; -- reduces checkpoint I/O operations and stabilizes ordinary-write throughput - before any mounted or RF3 claim. - -This is one large milestone. Instrumentation, bounded writeback, failure and -concurrency semantics, recovery equivalence, Linux performance, and conditional -mounted admission are deliverables inside Phase 171. +- reduces a current ordinary dirty entry from two WAL reads to one; +- reads a multi-block WAL record once for all snapshot entries that reference + that exact record; +- preserves the current disk format and complete-snapshot checkpoint rule; +- retains fail-closed validation before extent write or checkpoint progress; +- bounds temporary memory to one WAL record or one configured read chunk; +- keeps trim, wrap, padding, overwrite, direct BASE, retention, Sync, Close, + recovery, rebuild, and replication semantics unchanged; +- earns promotion only through same-run Linux and mounted evidence. ## Non-Goals -- No new WAL format, backend name, frontend protocol, or product selector. -- No staged append owner from Phase 170. -- No `io_uring`, direct I/O, raw device, SQPOLL, fixed buffer, FUA, or NVMe - atomic-write claim. -- No partial dirty-map snapshot that advances checkpoint past omitted entries. -- No disabled-flusher performance claim. -- No arbitrary sleep added to make benchmark samples look stable. -- No replication, authority, CSI, or Operation Layer semantic change. -- No WAL-read coalescing unless D2 evidence shows it is the next measured - limiter after extent-write coalescing. - -## Existing Product Seam - -The current `flusher.flushOnce` path is: - -```text -snapshot all latest dirty-map entries --> read one WAL header per entry and validate LSN/location --> read each current block from WAL --> WriteAt one block into its natural extent slot --> fsync the shared file --> persist checkpoint metadata --> advance WAL tail --> compare-and-delete each flushed dirty entry -``` - -This shape is correct but syscall-heavy. It also rereads WAL metadata when -`readFromWAL` materializes data after the first validation pass. The initial -change must target only extent writeback; WAL read materialization remains a -separate measured decision. - -The proven helper shape in `core/storage/parallelwal`: - -- sorts checkpoint LBAs; -- groups only physically contiguous destination blocks; -- caps each positioned extent write at 1 MiB; -- returns an explicit operation count; -- does not alter the WAL record format. - -Phase 171 may reuse the algorithm, not the parallel backend's header, lane, -extent-switch, or recovery model. +- No new WAL format, backend name, frontend, or public selector in D1-D4. +- No extent-write coalescing rejected by Phase 171. +- No staged append owner rejected by Phase 170. +- No `io_uring` candidate rejected by Phase 168. +- No `O_DIRECT`, raw device, fixed buffer, SQPOLL, FUA, or atomic-write claim. +- No trusting dirty-map metadata without revalidating on-disk record bytes. +- No volume-sized record cache or unbounded grouping map. +- No disabled-flusher or checkpoint-free performance claim. ## Required Invariants -1. The current superblock and WAL bytes remain unchanged. -2. A flush cycle advances in-memory or on-disk checkpoint only after every - current entry in its complete snapshot has been verified, materialized, - written, covered by a successful extent fsync, and followed by a successful - checkpoint-metadata write and fsync. -3. A failed extent write or fsync advances neither checkpoint nor recyclable - tail. Partial extent writes remain safe because recovery replays the - retained WAL. -4. A concurrent newer write to the same LBA remains visible and dirty. - Compare-and-delete may remove only the exact flushed LSN. -5. A WAL-slot/header mismatch fails the flush cycle closed. It removes no dirty - entry and advances no checkpoint unless durable checkpoint evidence proves - that exact entry is already obsolete. -6. Contiguous coalescing never crosses an LBA gap, block-size boundary, - configured maximum write size, or extent-region boundary. -7. Circular WAL wrap, padding, stale-slot detection, trim, ordinary records, - and multi-block record data offsets retain current behavior. -8. Foreground append and background extent writes may overlap only in disjoint - file regions. Flusher writeback and direct rebuild BASE installation need - an explicit extent ownership rule so a coalesced range cannot overwrite a - newer BASE block. -9. Recovery-retention and active rebuild pin floors continue to clamp - checkpoint/tail advancement exactly as today. -10. Sync retains its current target-head and fsync semantics. Checkpoint - optimization may not claim a higher durable frontier or hide a failed - flusher cycle. -11. Close rejects new writes, performs one final best-effort complete flush - while the file remains usable, and never closes the file while writeback - is active. -12. Instrumentation distinguishes WAL append, WAL readback, extent writeback, - fsync, checkpoint metadata, and cleanup work. Counters cannot turn a - partial cycle into a successful cycle. -13. A rejected candidate leaves default flusher behavior and all external - contracts unchanged. +1. Dirty metadata is an address hint, never proof that the WAL slot still + contains the expected record. +2. Every materialized record passes the existing decode and CRC validation + before any extent write. +3. Ordinary write validation matches exact LSN, LBA, type, length, flags, and + data range. +4. Trim validation produces one zero block only after exact trim identity is + proven. +5. Multi-block entries sharing a WAL offset may reuse bytes only when record + identity and each block's LSN/LBA/data offset are independently validated. +6. Ring padding and wrap are never exposed as a record and no read crosses the + WAL-region boundary. +7. A stale slot, short read, CRC mismatch, unsupported type, or metadata + disagreement fails the complete cycle closed: no dirty deletion, + checkpoint advance, or tail reuse. +8. Concurrent overwrite keeps the newer dirty entry through the existing + compare-and-delete contract. +9. Direct BASE and flusher ownership remains governed by the existing extent + locks; materialization does not create a second extent writer. +10. Checkpoint publication remains extent write -> extent fsync -> checkpoint + write -> checkpoint fsync -> tail publication. +11. Close, admission, pressure wakeup, recycle pins, and Sync cannot deadlock + with the candidate path. +12. A rejected candidate leaves the default path and all external contracts + unchanged. ## Deliverables -### D1. Correctness Hardening And Full-Pipeline Baseline +### D1. Record Geometry And Baseline Contract -- Add failure injection around checkpoint metadata write/fsync. Prove failure - advances neither in-memory checkpoint nor WAL tail, retry succeeds, and - crash/reopen uses only a durably published checkpoint. -- Require a checkpoint metadata fsync before any corresponding WAL-tail reuse. -- Repair or explicitly replace the current Close sequencing so the promised - final flush can run after new writes are fenced but before file close. Prove - dirty close/reopen and final-flush failure behavior. -- Define and test flusher-versus-direct-BASE extent ownership. A direct block - and a coalesced range that overlap must resolve according to the rebuild - bitmap/frontier contract rather than goroutine timing. -- Make an unexplained WAL-slot/header mismatch fail the cycle closed with no - dirty deletion, checkpoint advance, or tail reuse. Only explicit durable - checkpoint evidence may classify an entry as safely obsolete. +- Extend the dirty-entry in-memory contract with only the geometry needed to + size one record read. Populate it at ordinary append, trim, WriteBatch, + multi-block append, and recovery replay. +- Prove this metadata is reconstructed after reopen and is never serialized as + a new disk format. +- Add deterministic counters for logical dirty entries, unique WAL records, + materialization reads/bytes, reused-record hits, and validation failures. +- Add a five-run Linux baseline for ordinary, explicit batch, multi-block + opt-in, wrap, and scattered workloads. Cover legacy trim records with a + deterministic recovery fixture because `WALStore` has no public trim API. +- Admit D2 only when at least four of five sequential samples and four of five + scattered samples each report: + - header reads per validated record in `[0.95, 1.05]`; + - full-record reads per validated record in `[0.95, 1.05]`; + - combined materialization reads per validated record at least `1.90`. +- Require a dedicated scoped `strace` control to corroborate the product + counter shape. Whole-process counts may be reported as qualitative context + but cannot satisfy admission. -- Add product-owned counters for snapshot entries, validated/stale entries, - WAL header/data read operations and bytes, extent write operations and - bytes, maximum extent write size, fsync time/count, checkpoint metadata - operations, successful/failed cycles, and cycle latency. -- Extend the Phase 170 ordinary-Write benchmark rather than creating a - synthetic storage backend. -- Run 4 KiB ordinary Write and explicit 16-block WriteBatch with 1/2/4/8 - writers, normal 100 ms flusher cadence, explicit final Sync, and complete - final drain. -- Report five-run median/range, p50/p95/p99, allocations, foreground stage - metrics, flusher metrics, CPU, selected syscalls, checkpoint coverage, and - exact Sync cadence. -- Report foreground Write duration, final Sync duration, and final drain - duration separately. Throughput admission uses the foreground interval, - while drain improvement remains a separately named operational result. -- Report contiguous-run count/distribution and the theoretical minimum bounded - extent-write operations for both sequential and randomized-LBA workloads. - D2 is not admitted when realistic snapshots have no material coalescing - opportunity. -- Verify counters against deterministic small fixtures and external - `strace` where available. Product counters are authoritative for scoped - work; whole-process `strace` remains qualitative unless a dedicated test - binary isolates the operation. +### D2. Single-Read Fail-Closed Materialization -### D2. Bounded Contiguous Extent Writeback +- Add one internal disabled-by-default comparison mode. +- Read each ordinary or trim record once at its exact bounded size. +- Decode and validate with the existing CRC and semantic checks; do not add a + fast parser that bypasses `decodeWALEntry`. +- Return one block view/copy only after validation. +- Prove ordinary write, trim, gapped/reverse snapshot, ring-end padding, wrap, + short read, stale slot, corrupt header, corrupt payload, flags, and + unsupported-type behavior. +- Inject first/middle/final materialization failures and prove no false + checkpoint or dirty deletion. -- Add one internal, disabled-by-default comparison mode before changing the - shipped default. -- Sort the existing complete dirty snapshot by LBA without changing which - entries are included. -- Materialize and write contiguous destination LBAs in bounded chunks of at - most 1 MiB. -- Keep only one bounded data chunk live at a time; do not build an additional - volume-sized data map. -- Preserve fail-closed stale-slot handling, trim zeroing, multi-block - `dataOffset`, max-LSN tracking, extent-fsync then - checkpoint-write/fsync ordering, WAL-tail advancement, and - compare-and-delete behavior. -- Prove contiguous, gapped, reverse snapshot order, overwrite, trim, - multi-block, wrap, maximum chunk, final partial chunk, and empty-cycle - behavior. -- Inject first/middle/final extent-write failure and fsync failure. Each must - retain recovery through the unchanged WAL and publish no false checkpoint. +### D3. Shared Multi-Block Record Materialization -### D3. Concurrency, Scheduling, And Optional WAL Readback Decision +- Order the complete snapshot by WAL record identity without omitting entries. +- Read one multi-block record once and validate every referenced block's + expected LSN, LBA, length, and data offset. +- Keep at most one bounded decoded record live; release it before moving to the + next record. +- Prove partial overwrite of a shared record leaves newer blocks dirty while + safely flushing still-current blocks. +- Prove malformed `Reserved`, total length, offset, and wrap metadata fail the + whole cycle closed. -- Exercise foreground Write/WriteBatch while a large flush cycle is active, - including repeated same-LBA overwrite and WAL pressure wakeups. -- Exercise direct BASE installation against overlapping and adjacent flusher - ranges; no result may depend on physical write completion order. -- Prove admission, flusher, Sync, retention pin, and Close cannot deadlock. -- Measure flusher-cycle occupancy, foreground p99, extent operations per block, - and WAL read operations per block after D2. -- If WAL readback is then a material limiter, add one separately gated bounded - read-materialization change that retains per-record LSN/type/length checks - and handles ring wrap. Otherwise record the no-change decision. -- Do not combine fsync scheduling or group-committer redesign into this - deliverable unless a dedicated trace proves duplicate/concurrent fsync is - the remaining dominant cost. +### D4. Concurrency, Recovery, And Lifecycle Equivalence -### D4. Recovery, Retention, Rebuild, And Replication Equivalence - -- Run existing WAL recovery, corruption, typed-failure, flusher, retention, - recycle-pin, direct-frontier, and close/reopen suites against - candidate-created files. -- Add crash windows after extent fsync, after checkpoint pwrite, after - checkpoint fsync, and before/after WAL-tail publication. -- Prove `ScanLBAs`, catch-up, direct BASE install, `AdvanceFrontier`, and - returned-replica rebuild retain their current contracts. -- Exercise checkpoint advancement under an active recycle-floor pin and after - pin release. -- Run storage race coverage and RF1/RF3 logical replication component tests. +- Run foreground Write/WriteBatch and repeated same-LBA overwrite during large + materialization cycles. +- Exercise direct BASE overlap, pressure wakeups, recycle-floor pins, Sync, + Close, and final-flush failure under race instrumentation. +- Reopen candidate-created files and run corruption, typed-failure, retention, + `ScanLBAs`, catch-up, returned-replica rebuild, RF1, and RF3 component suites. +- Add crash windows before materialization, after extent write/fsync, and + around checkpoint/tail publication. - No new recovery or replication branch is allowed. ### D5. Comparable Linux Performance Decision -- Compare candidate and unchanged default flusher in one rotated m02 session - with five one-second repetitions. -- Include ordinary 4 KiB Write and explicit 16-block WriteBatch at 1/2/4/8 - writers with identical flusher, Sync, file, and checkpoint settings. -- Report median/range, p50/p95/p99, allocations, CPU, scoped/selected syscalls, - append and flusher stage metrics, extent operations per block, checkpoint - coverage, pressure waits, and failed-cycle counters. Foreground, final Sync, - and final drain durations must remain separate. -- Admit the candidate only if: +- Compare candidate and unchanged default in one rotated m02 run with five + one-second repetitions and identical 100 ms flusher/Sync/drain settings. +- Cover ordinary 4 KiB, scattered 4 KiB, explicit 16-block batch, and + multi-block opt-in at 1/2/4/8 writers where applicable; keep trim as a + correctness fixture rather than inventing a benchmark-only product API. +- Report foreground throughput and p50/p95/p99 separately from final Sync and + drain, plus allocations, CPU, scoped syscalls, failed cycles, checkpoint + coverage, and exact materialization counters. +- Admit only if: + - WAL materialization reads per validated ordinary entry fall by at least + 45% and match scoped `strace`; - one-writer ordinary throughput is at least 95% of baseline; - - four-writer ordinary throughput improves by at least 1.25x; - - candidate four-writer median is not below candidate one-writer median - unless measured device saturation explains the ceiling; - - extent `WriteAt` operations per contiguous block fall materially and match - deterministic counter/trace evidence; - - ordinary four-writer range is at most `1.50x` and improves materially from - the Phase 170 `2.936x` baseline; - - p99, WAL pressure, failed cycles, checkpoint coverage, and cleanup remain - bounded and correct. + - four-writer ordinary median improves by at least 1.15x; + - candidate four-writer range is at most 1.50x; + - p99 does not regress by more than 10%; + - multi-block reuse reduces physical reads without increasing corruption or + recovery ambiguity; + - failed cycles remain zero and checkpoint coverage remains complete. ### D6. Mounted RF1 And RF3 Close Gate - Run only if D5 admits the candidate. -- Build matching product and CSI images from the exact candidate commit. -- Run mounted NVMe/TCP RF1 concurrent Write/Flush/Read/checksum, durable +- Build exact matching product and CSI images. +- Run mounted NVMe/TCP RF1 concurrent write/flush/read/checksum, durable restart, and sustained writeback pressure. -- Run RF3 sync-quorum with a delayed non-quorum peer, catch-up/rebuild, - restart, honest status, and continued mounted I/O. -- Compare baseline and candidate in the same lab session. -- Finish with product-owned cleanup verification and zero Kubernetes, NVMe, - iSCSI, process, and durable-path residue. -- Change the default flusher only after this gate passes. +- Run RF3 sync-quorum with delayed peer, catch-up/rebuild, restart, honest + status, and continued mounted I/O. +- Compare baseline and candidate in the same lab session and finish with + product-owned zero-residue cleanup. +- Promote the candidate only after this gate passes; otherwise remove it. ## Stop Rules Stop and remove the candidate if: -- D1 does not show meaningful extent-write or WAL-read amplification; -- D1 realistic snapshots have too few contiguous runs for bounded coalescing - to reduce extent operations materially; -- operation reduction does not improve ordinary Write throughput or stability; -- coalescing requires omitting dirty entries or advancing checkpoint over - incomplete work; -- bounded writeback cannot retain trim, multi-block, wrap, stale-slot, and - overwrite semantics; -- a WAL-slot mismatch can delete dirty state or permit checkpoint progress - without durable obsolescence evidence; -- pressure, Sync, Close, or recycle pins can deadlock with the flusher; -- a failed partial cycle can become a visible checkpoint; -- checkpoint metadata is not durable before the corresponding WAL bytes become - reusable; -- Close cannot fence new writes while still completing its promised final - flush; -- direct BASE and flusher overlap has no deterministic ownership rule; -- performance depends on disabling normal flush, fsync, checkpoint, recovery, - or retention work; -- only explicit WriteBatch improves while ordinary Write remains unstable. +- D1 does not reproduce stable duplicate WAL reads; +- exact record sizing requires trusting unverified disk metadata; +- one-read materialization weakens CRC/type/LSN/LBA/length/offset checks; +- grouping can omit a dirty entry or advance checkpoint over incomplete work; +- temporary memory grows with volume size rather than one bounded record; +- any failure deletes dirty state or publishes checkpoint/tail progress; +- concurrency or lifecycle tests deadlock; +- physical read reduction does not improve ordinary throughput or stability; +- only the opt-in multi-block path improves. -An honest rejection is a valid Phase 171 outcome. It must leave the current -disk format, default flusher, and all frontend/replication/operation contracts -intact. +An honest rejection is a valid Phase 172 result. It must leave the current disk +format, default flusher, and all frontend, recovery, replication, and Operation +Layer contracts intact. ## Exit Criteria ```text -checkpoint/Close/BASE correctness hardening plus full-pipeline evidence --> bounded contiguous extent writeback --> concurrency and optional WAL-read decision --> unchanged recovery/retention/rebuild/replication semantics +record geometry and duplicate-read evidence +-> disabled single-read materialization +-> bounded shared-record reuse +-> concurrency/recovery/lifecycle equivalence -> same-run Linux performance decision -> mounted RF1/RF3 only if admitted -> promote or remove ``` - -The milestone succeeds by proving or disproving a complete shipped-path -improvement, not by reducing one counter in isolation. diff --git a/seaweed-block/internal/docs/finished-plans/phase171_finishedplan_default_walstore_checkpoint_pipeline.md b/seaweed-block/internal/docs/finished-plans/phase171_finishedplan_default_walstore_checkpoint_pipeline.md new file mode 100644 index 0000000000..1718e8b536 --- /dev/null +++ b/seaweed-block/internal/docs/finished-plans/phase171_finishedplan_default_walstore_checkpoint_pipeline.md @@ -0,0 +1,385 @@ +# Finished Plan: Phase 171 Default WALStore Checkpoint Pipeline + +Status: complete at D1. Correctness hardening and instrumentation shipped; the +bounded extent-write candidate was rejected by its pre-implementation +admission gate, so D2-D6 were intentionally skipped. + +## Final Outcome + +Phase 171 strengthened the shipped `walstore` before attempting optimization: + +- checkpoint metadata is written and fsynced before in-memory checkpoint or + recyclable WAL-tail publication; +- failed checkpoint publication retains WAL recovery and permits a safe retry; +- `Close` fences new mutations, performs its final flush while the file is + usable, and waits for in-flight storage work; +- direct rebuild BASE and flusher extent writes have deterministic ownership; +- stale, corrupt, or unsupported dirty WAL records fail the cycle closed; +- full pipeline counters separate validation, WAL readback, extent writeback, + fsync, checkpoint metadata, cycle outcome, and bounded-write opportunity; +- dual-lane recovery now seals both foreground append and autonomous timer + drain before its barrier, then restores steady context atomically. + +Exact Linux QA on `2c54a61` passed 100 race repetitions of the barrier/timer +tests, 1,000 Pillar3 convergence repetitions, all SIGKILL checkpoint windows, +storage/recovery/transport/replication regression, and storage vet. + +The same clean Linux run denied D2: + +```text +sequential_writers_4_extent_write_ops_per_entry_median=1.000 +sequential_writers_4_extent_written_min_write_ops_per_entry_median=0.3522 +scattered_writers_4_extent_write_ops_per_entry_median=1.000 +scattered_writers_4_extent_written_min_write_ops_per_entry_median=0.5547 +sequential_opportunity_pass_count=1 +scattered_opportunity_pass_count=5 +scattered_coalescible_pass_count=5 +d2_bounded_extent_candidate_admitted=false +next_recommendation=stop_before_bounded_extent_writeback +``` + +Contiguous writeback had useful individual samples, but sequential opportunity +met the required threshold in only one of five runs. The threshold was not +relaxed after seeing the result. No comparison mode, default change, disk +format, or mounted claim was added. + +## Archived Original Plan + +The remainder of this document preserves the plan as written before the D1 +decision. Prospective language below describes the evaluated hypothesis, not +the final shipped result. + +Phase 170 proved that WAL append-call coalescing is mechanically effective but +not sufficient under the complete default `walstore` workload: + +```text +ordinary writers=4 64.09 MiB/s +explicit batch writers=4 47.22 MiB/s +batch/ordinary 0.737x +ordinary WriteAt calls/entry 1.000 +batch WriteAt calls/entry 0.06250 +paired batch gains 2/5 +ordinary four-writer range 2.936x +batch four-writer range 3.500x +``` + +The batch control reduced WAL `WriteAt` calls by about 16x, yet throughput and +stability did not improve. A staged append owner was therefore rejected before +implementation. + +The next measured seam is the other half of the shipped persistence pipeline. +At phase start, the default flusher snapshotted the complete dirty map and, for +each current entry, read and validated WAL location metadata, read block data, +issued one extent `WriteAt`, fsynced the shared file, persisted the checkpoint, +and advanced the recyclable tail. This work competed with foreground WAL +append on the same file and exposed only flush-count and byte-count evidence +before D1. + +The plan review also found correctness debt in this path that must be fixed +before optimization: + +- `persistCheckpoint` currently updates the in-memory checkpoint before its + superblock write succeeds, so a later cycle can incorrectly treat a failed + checkpoint as reusable; +- checkpoint metadata is not fsynced before in-memory WAL-tail reuse; +- `Close` marks the store closed before `flusher.Stop` requests its final + cycle, so that promised final flush currently exits without work; +- default `walstore` has no explicit extent-write ownership rule between + flusher writeback and direct rebuild BASE installation; +- a WAL-slot mismatch currently deletes the dirty entry and continues, even + though the flusher has not proved that entry was already durably + checkpointed. + +Phase 167 already proved that bounded contiguous checkpoint writes can reduce +writeback syscall amplification in the opt-in `parallel-walstore`. Phase 171 +tests the corresponding mechanism in the default `walstore`, without changing +its disk format, recovery rules, or public storage contract. + +## Goal + +Build one evidence-gated checkpoint/writeback improvement for the shipped +`WALStore` that: + +- first makes checkpoint publication, tail reuse, Close, and direct BASE + overlap failure-safe; +- measures foreground WAL and background checkpoint work independently; +- preserves the current complete-snapshot checkpoint invariant; +- materializes every verified latest dirty block before advancing checkpoint; +- combines contiguous extent LBAs into bounded positioned writes; +- retains compare-and-delete protection against concurrent overwrite; +- keeps circular-WAL validation, retention pins, Sync, recovery, direct BASE + install, and rebuild semantics unchanged; +- reduces checkpoint I/O operations and stabilizes ordinary-write throughput + before any mounted or RF3 claim. + +This is one large milestone. Instrumentation, bounded writeback, failure and +concurrency semantics, recovery equivalence, Linux performance, and conditional +mounted admission are deliverables inside Phase 171. + +## Non-Goals + +- No new WAL format, backend name, frontend protocol, or product selector. +- No staged append owner from Phase 170. +- No `io_uring`, direct I/O, raw device, SQPOLL, fixed buffer, FUA, or NVMe + atomic-write claim. +- No partial dirty-map snapshot that advances checkpoint past omitted entries. +- No disabled-flusher performance claim. +- No arbitrary sleep added to make benchmark samples look stable. +- No replication, authority, CSI, or Operation Layer semantic change. +- No WAL-read coalescing unless D2 evidence shows it is the next measured + limiter after extent-write coalescing. + +## Existing Product Seam + +The current `flusher.flushOnce` path is: + +```text +snapshot all latest dirty-map entries +-> read one WAL header per entry and validate LSN/location +-> read each current block from WAL +-> WriteAt one block into its natural extent slot +-> fsync the shared file +-> persist checkpoint metadata +-> advance WAL tail +-> compare-and-delete each flushed dirty entry +``` + +This shape is correct but syscall-heavy. It also rereads WAL metadata when +`readFromWAL` materializes data after the first validation pass. The initial +change must target only extent writeback; WAL read materialization remains a +separate measured decision. + +The proven helper shape in `core/storage/parallelwal`: + +- sorts checkpoint LBAs; +- groups only physically contiguous destination blocks; +- caps each positioned extent write at 1 MiB; +- returns an explicit operation count; +- does not alter the WAL record format. + +Phase 171 may reuse the algorithm, not the parallel backend's header, lane, +extent-switch, or recovery model. + +## Required Invariants + +1. The current superblock and WAL bytes remain unchanged. +2. A flush cycle advances in-memory or on-disk checkpoint only after every + current entry in its complete snapshot has been verified, materialized, + written, covered by a successful extent fsync, and followed by a successful + checkpoint-metadata write and fsync. +3. A failed extent write or fsync advances neither checkpoint nor recyclable + tail. Partial extent writes remain safe because recovery replays the + retained WAL. +4. A concurrent newer write to the same LBA remains visible and dirty. + Compare-and-delete may remove only the exact flushed LSN. +5. A WAL-slot/header mismatch fails the flush cycle closed. It removes no dirty + entry and advances no checkpoint unless durable checkpoint evidence proves + that exact entry is already obsolete. +6. Contiguous coalescing never crosses an LBA gap, block-size boundary, + configured maximum write size, or extent-region boundary. +7. Circular WAL wrap, padding, stale-slot detection, trim, ordinary records, + and multi-block record data offsets retain current behavior. +8. Foreground append and background extent writes may overlap only in disjoint + file regions. Flusher writeback and direct rebuild BASE installation need + an explicit extent ownership rule so a coalesced range cannot overwrite a + newer BASE block. +9. Recovery-retention and active rebuild pin floors continue to clamp + checkpoint/tail advancement exactly as today. +10. Sync retains its current target-head and fsync semantics. Checkpoint + optimization may not claim a higher durable frontier or hide a failed + flusher cycle. +11. Close rejects new writes, performs one final best-effort complete flush + while the file remains usable, and never closes the file while writeback + is active. +12. Instrumentation distinguishes WAL append, WAL readback, extent writeback, + fsync, checkpoint metadata, and cleanup work. Counters cannot turn a + partial cycle into a successful cycle. +13. A rejected candidate leaves default flusher behavior and all external + contracts unchanged. + +## Deliverables + +### D1. Correctness Hardening And Full-Pipeline Baseline + +Status: complete and independently QA-validated. + +- Add failure injection around checkpoint metadata write/fsync. Prove failure + advances neither in-memory checkpoint nor WAL tail, retry succeeds, and + crash/reopen uses only a durably published checkpoint. +- Require a checkpoint metadata fsync before any corresponding WAL-tail reuse. +- Repair or explicitly replace the current Close sequencing so the promised + final flush can run after new writes are fenced but before file close. Prove + dirty close/reopen and final-flush failure behavior. +- Define and test flusher-versus-direct-BASE extent ownership. A direct block + and a coalesced range that overlap must resolve according to the rebuild + bitmap/frontier contract rather than goroutine timing. +- Make an unexplained WAL-slot/header mismatch fail the cycle closed with no + dirty deletion, checkpoint advance, or tail reuse. Only explicit durable + checkpoint evidence may classify an entry as safely obsolete. + +- Add product-owned counters for snapshot entries, validated/stale entries, + WAL header/data read operations and bytes, extent write operations and + bytes, maximum extent write size, fsync time/count, checkpoint metadata + operations, successful/failed cycles, and cycle latency. +- Extend the Phase 170 ordinary-Write benchmark rather than creating a + synthetic storage backend. +- Run 4 KiB ordinary Write and explicit 16-block WriteBatch with 1/2/4/8 + writers, normal 100 ms flusher cadence, explicit final Sync, and complete + final drain. +- Report five-run median/range, p50/p95/p99, allocations, foreground stage + metrics, flusher metrics, CPU, selected syscalls, checkpoint coverage, and + exact Sync cadence. +- Report foreground Write duration, final Sync duration, and final drain + duration separately. Throughput admission uses the foreground interval, + while drain improvement remains a separately named operational result. +- Report contiguous-run count/distribution and the theoretical minimum bounded + extent-write operations for both sequential and randomized-LBA workloads. + D2 is not admitted when realistic snapshots have no material coalescing + opportunity. +- Verify counters against deterministic small fixtures and external + `strace` where available. Product counters are authoritative for scoped + work; whole-process `strace` remains qualitative unless a dedicated test + binary isolates the operation. + +### D2. Bounded Contiguous Extent Writeback + +Status: skipped because the D1 admission gate returned +`d2_bounded_extent_candidate_admitted=false`. + +- Add one internal, disabled-by-default comparison mode before changing the + shipped default. +- Sort the existing complete dirty snapshot by LBA without changing which + entries are included. +- Materialize and write contiguous destination LBAs in bounded chunks of at + most 1 MiB. +- Keep only one bounded data chunk live at a time; do not build an additional + volume-sized data map. +- Preserve fail-closed stale-slot handling, trim zeroing, multi-block + `dataOffset`, max-LSN tracking, extent-fsync then + checkpoint-write/fsync ordering, WAL-tail advancement, and + compare-and-delete behavior. +- Prove contiguous, gapped, reverse snapshot order, overwrite, trim, + multi-block, wrap, maximum chunk, final partial chunk, and empty-cycle + behavior. +- Inject first/middle/final extent-write failure and fsync failure. Each must + retain recovery through the unchanged WAL and publish no false checkpoint. + +### D3. Concurrency, Scheduling, And Optional WAL Readback Decision + +Status: skipped with the rejected D2 candidate. WAL read materialization is +carried into Phase 172 as a separate measured hypothesis, not appended to a +failed coalescing candidate. + +- Exercise foreground Write/WriteBatch while a large flush cycle is active, + including repeated same-LBA overwrite and WAL pressure wakeups. +- Exercise direct BASE installation against overlapping and adjacent flusher + ranges; no result may depend on physical write completion order. +- Prove admission, flusher, Sync, retention pin, and Close cannot deadlock. +- Measure flusher-cycle occupancy, foreground p99, extent operations per block, + and WAL read operations per block after D2. +- If WAL readback is then a material limiter, add one separately gated bounded + read-materialization change that retains per-record LSN/type/length checks + and handles ring wrap. Otherwise record the no-change decision. +- Do not combine fsync scheduling or group-committer redesign into this + deliverable unless a dedicated trace proves duplicate/concurrent fsync is + the remaining dominant cost. + +### D4. Recovery, Retention, Rebuild, And Replication Equivalence + +Status: candidate-specific work skipped. D1 nevertheless ran the unchanged +recovery, retention, rebuild, replication, crash, and race regressions. + +- Run existing WAL recovery, corruption, typed-failure, flusher, retention, + recycle-pin, direct-frontier, and close/reopen suites against + candidate-created files. +- Add crash windows after extent fsync, after checkpoint pwrite, after + checkpoint fsync, and before/after WAL-tail publication. +- Prove `ScanLBAs`, catch-up, direct BASE install, `AdvanceFrontier`, and + returned-replica rebuild retain their current contracts. +- Exercise checkpoint advancement under an active recycle-floor pin and after + pin release. +- Run storage race coverage and RF1/RF3 logical replication component tests. +- No new recovery or replication branch is allowed. + +### D5. Comparable Linux Performance Decision + +Status: skipped because D2 was not admitted. + +- Compare candidate and unchanged default flusher in one rotated m02 session + with five one-second repetitions. +- Include ordinary 4 KiB Write and explicit 16-block WriteBatch at 1/2/4/8 + writers with identical flusher, Sync, file, and checkpoint settings. +- Report median/range, p50/p95/p99, allocations, CPU, scoped/selected syscalls, + append and flusher stage metrics, extent operations per block, checkpoint + coverage, pressure waits, and failed-cycle counters. Foreground, final Sync, + and final drain durations must remain separate. +- Admit the candidate only if: + - one-writer ordinary throughput is at least 95% of baseline; + - four-writer ordinary throughput improves by at least 1.25x; + - candidate four-writer median is not below candidate one-writer median + unless measured device saturation explains the ceiling; + - extent `WriteAt` operations per contiguous block fall materially and match + deterministic counter/trace evidence; + - ordinary four-writer range is at most `1.50x` and improves materially from + the Phase 170 `2.936x` baseline; + - p99, WAL pressure, failed cycles, checkpoint coverage, and cleanup remain + bounded and correct. + +### D6. Mounted RF1 And RF3 Close Gate + +Status: skipped because D5 had no admitted candidate. + +- Run only if D5 admits the candidate. +- Build matching product and CSI images from the exact candidate commit. +- Run mounted NVMe/TCP RF1 concurrent Write/Flush/Read/checksum, durable + restart, and sustained writeback pressure. +- Run RF3 sync-quorum with a delayed non-quorum peer, catch-up/rebuild, + restart, honest status, and continued mounted I/O. +- Compare baseline and candidate in the same lab session. +- Finish with product-owned cleanup verification and zero Kubernetes, NVMe, + iSCSI, process, and durable-path residue. +- Change the default flusher only after this gate passes. + +## Stop Rules + +Stop and remove the candidate if: + +- D1 does not show meaningful extent-write or WAL-read amplification; +- D1 realistic snapshots have too few contiguous runs for bounded coalescing + to reduce extent operations materially; +- operation reduction does not improve ordinary Write throughput or stability; +- coalescing requires omitting dirty entries or advancing checkpoint over + incomplete work; +- bounded writeback cannot retain trim, multi-block, wrap, stale-slot, and + overwrite semantics; +- a WAL-slot mismatch can delete dirty state or permit checkpoint progress + without durable obsolescence evidence; +- pressure, Sync, Close, or recycle pins can deadlock with the flusher; +- a failed partial cycle can become a visible checkpoint; +- checkpoint metadata is not durable before the corresponding WAL bytes become + reusable; +- Close cannot fence new writes while still completing its promised final + flush; +- direct BASE and flusher overlap has no deterministic ownership rule; +- performance depends on disabling normal flush, fsync, checkpoint, recovery, + or retention work; +- only explicit WriteBatch improves while ordinary Write remains unstable. + +An honest rejection is a valid Phase 171 outcome. It must leave the current +disk format, default flusher, and all frontend/replication/operation contracts +intact. + +## Exit Criteria + +```text +checkpoint/Close/BASE correctness hardening plus full-pipeline evidence +-> bounded contiguous extent writeback +-> concurrency and optional WAL-read decision +-> unchanged recovery/retention/rebuild/replication semantics +-> same-run Linux performance decision +-> mounted RF1/RF3 only if admitted +-> promote or remove +``` + +The milestone succeeds by proving or disproving a complete shipped-path +improvement, not by reducing one counter in isolation. diff --git a/seaweed-block/internal/docs/product-roadmap.md b/seaweed-block/internal/docs/product-roadmap.md index d4b2e9e554..6f484492bd 100644 --- a/seaweed-block/internal/docs/product-roadmap.md +++ b/seaweed-block/internal/docs/product-roadmap.md @@ -130,10 +130,10 @@ This is the short internal roadmap. Keep it current and readable. - Phase 167 closed as an opt-in Parallel Write Engine research result. Phase 168 then rejected native `io_uring` execution, Phase 169 rejected a segmented group-commit format, and Phase 170 rejected a default-WAL staged - append owner before implementation because existing-format batching reduced - WAL writes but did not produce stable concurrent throughput. Phase 171 now - measures and optimizes the shipped `walstore` checkpoint/writeback half - rather than adding another backend or append queue. + append owner. Phase 171 hardened the shipped checkpoint path and rejected + bounded extent coalescing at its D1 admission gate. Phase 172 now targets the + stable two-read WAL materialization amplification without adding another + backend or append queue. Do not skip from scripts directly to mutating operator lifecycle. Helm has stabilized the installation contract, and Phase 35 added read-only CRD status, @@ -601,11 +601,15 @@ rebuild, delete safety, or cleanup must start as a separate gated phase. entry, but four-writer throughput was only `0.737x` ordinary Write, paired gain passed only `2/5` samples, and run ranges exceeded `2.9x`. The staged owner was stopped before implementation. -- Active next: Phase 171 instruments and optimizes the default `walstore` - checkpoint/writeback path. It may port bounded contiguous extent writes from - the Phase 167 research backend only if full-pipeline evidence shows - writeback amplification and the complete flusher/recovery contract remains - intact. Direct I/O, fixed buffers, FUA, and device atomic writes remain later +- Closed hardening: Phase 171 made checkpoint/tail publication, Close, direct + BASE overlap, stale-slot handling, and dual-lane barrier sealing fail closed. + Its Linux admission gate rejected bounded extent coalescing because + sequential opportunity was stable in only `1/5` samples. +- Active next: Phase 172 tests one bounded WAL materialization pipeline. The + default flusher currently performs one header read plus one full-record read + per validated dirty entry; the candidate may replace those with one + fully-validated read and bounded same-record reuse. Direct I/O, fixed + buffers, FUA, raw devices, and device atomic writes remain later evidence-gated decisions. - Protocol hardening now has a dedicated working area under `internal/docs/protocol/`. New protocol semantics should update the control @@ -1249,10 +1253,14 @@ Approximate engineering effort if scope remains tight: `WriteAt` calls by about 16x but did not provide stable four-writer throughput headroom, so no owner or selector was added. The finished plan is `internal/docs/finished-plans/phase170_finishedplan_default_walstore_staged_commit.md`. -- Phase 171 Default WALStore Checkpoint Pipeline is active. It starts by - measuring foreground/background I/O separately, then may add bounded - contiguous extent writeback to the shipped flusher before any mounted or RF3 - claim. The contract is `internal/docs/current-plan.md`. +- Phase 171 Default WALStore Checkpoint Pipeline is closed at D1. Correctness + hardening and full-pipeline evidence passed; bounded extent writeback was + rejected by its admission gate. The finished plan is + `internal/docs/finished-plans/phase171_finishedplan_default_walstore_checkpoint_pipeline.md`. +- Phase 172 WAL Materialization Pipeline is active. It tests whether replacing + duplicate per-entry WAL reads with one bounded, fully validated + materialization improves the shipped backend. The contract is + `internal/docs/current-plan.md`. - Phase 41-44 are the Operation Layer v0.5 release train: lifecycle-owner foundation, real API/admission proof, first bounded finalizer mutation, and delete lifecycle close gate. diff --git a/seaweed-block/internal/docs/qa-assignments/phase171-d1-checkpoint-pipeline-qa-signoff.md b/seaweed-block/internal/docs/qa-assignments/phase171-d1-checkpoint-pipeline-qa-signoff.md new file mode 100644 index 0000000000..213add7915 --- /dev/null +++ b/seaweed-block/internal/docs/qa-assignments/phase171-d1-checkpoint-pipeline-qa-signoff.md @@ -0,0 +1,81 @@ +# Phase 171 D1 Checkpoint Pipeline QA Sign-off + +Verdict: PASS for D1 correctness and baseline gates; D2 admission rejected by +design. + +## Source + +```text +git_sha=2c54a61559a9bfdb11d2a0e8234348a81ff4fe7d +git_dirty=false +go_version=go1.25.0 linux/amd64 +cgo_enabled=1 +``` + +## Correctness + +```text +transport_race_repetitions=100 +transport_race_status=pass +pillar3_nonrace_repetitions=1000 +pillar3_nonrace_status=pass +focused_repetitions=20 +focused_status=pass +sigkill_repetitions=20 +sigkill_status=pass +race_repetitions=10 +race_status=pass +storage_recovery_transport_replication_regression=pass +go_vet_storage=pass +checkpoint_metadata_durable_before_tail_reuse=true +stale_or_corrupt_dirty_record_fails_closed=true +close_lifecycle_fence=true +direct_base_ownership_restart_safe=true +phase171_checkpoint_correctness_status=ok +``` + +The prior Pillar3 flake was a product boundary defect: the recovery adapter did +not seal the resident WalShipper timer before `BarrierReq`. The fix serializes +foreground append, autonomous drain, barrier cut, and steady-context handoff +under the shipper owner. No race finding, convergence failure, or teardown +hang remained. + +## Admission + +```text +phase171_walstore_checkpoint_baseline_status=ok +sequential_writers_4_mibps_median=44.54 +scattered_writers_4_mibps_median=42.72 +batch_writers_4_mibps_median=54.81 +sequential_writers_4_extent_write_ops_per_entry_median=1.000 +sequential_writers_4_extent_written_min_write_ops_per_entry_median=0.3522 +scattered_writers_4_extent_write_ops_per_entry_median=1.000 +scattered_writers_4_extent_written_min_write_ops_per_entry_median=0.5547 +sequential_opportunity_pass_count=1 +scattered_opportunity_pass_count=5 +scattered_coalescible_pass_count=5 +d2_bounded_extent_candidate_admitted=false +next_recommendation=stop_before_bounded_extent_writeback +``` + +The scoped qualitative syscall control used +`BenchmarkPhase167WALStoreContention/writers_4` with 67,539 logical writes: + +```text +pread64_calls=155282 +pwrite64_calls=155304 +fsync_calls=44 +``` + +The gate passed as a mechanism and rejected the candidate as a decision. +Sequential bounded-write opportunity met the required threshold in only one +of five samples. D2-D6 were not run and the threshold was not changed after +observing the result. + +## Evidence + +QA archive SHA256: +`5D6B3E83798E88992A17A719405BD793BBB8A3107761541F543B8611262D5BFE`. + +Final cleanup found no block residue or QA process. The shared worktree was not +modified by QA.