Skip to content

[Muse][GC] GC09: Completion-gate liveness under D-1 and D-N71(b) - #1

Closed
JustinGaoF wants to merge 1 commit into
pwal/gc08from
pwal/gc09-muse
Closed

JustinGaoF wants to merge 1 commit into
pwal/gc08from
pwal/gc09-muse

Conversation

@JustinGaoF

Copy link
Copy Markdown
Owner

[GC] GC09: completion-gate liveness under D-1 and D-N71(b)

Reviewer question: at wal_partitions > 1, can any listener-suppressed
append error, shutdown, soft background error, or released failed range
leave a parked writer hanging, failing when N=1 would succeed, or
succeeding with data above a hole? Check the five places that answer it:
the suppression override in WALIOStatusCheck/HandleKnownErrors, the
shutdown leg and waiter drain in CloseHelper, the failed-range-only
error leg in WaitForWalDurability, the flush cutoff plus taint in
ResumeImpl/ClearWalDurabilityBGError, and the N>1-only tracking
lift in ResumeImpl.

D-N71: (b) (dispatcher blank, Recommended). A parked gate fails only on
a failed WAL range at or below its target, on taint from a released
range, or on shutdown; every other background error reparks it.

Gate exits (Q1-Q4 together):

Condition Outcome
Frontier covers target, no taint OK
Failed WAL range at/below target Stored background error
Target inside a tainted interval Aborted (names the released range)
Shutdown, target uncovered ShutdownInProgress
Any other stored background error Repark; OK once covered

Q1 -- Suppressed WAL append errors still stop the DB [G-13]

Property: at N>1 a WAL append failure whose record never landed ends in
the background-error state with its N=1 severity even when a listener
suppresses it; listeners are still notified; suppression of
non-append errors and all N=1 suppression is unchanged.

How: two-phase. HandleKnownErrors takes is_wal_append_failure and
ignores the listener's override only for true append-misses; the
round-12/12.1 > guard is untouched. WALIOStatusCheck publishes
normally, then, only if suppressed (GetBGError().ok()) and the range
is still IsOutstanding on the tracker, re-publishes with the flag
set. A failure after the record landed (sync) leaves nothing pinned,
so its suppression stands. HandleMemTableInsertFailure records the
failed applied range at both call sites so an insert failure pins its
gates the same way.

Evidence: SuppressedWalAppendErrorStillStopsDb (N=2, listener
suppresses, non-file-scope non-retryable IOError; W fails bounded,
GetBGError() NOK; recovery via point-in-time reopen, the GC08 path),
SuppressedRetryableErrorWithoutAutoRecovery
(max_bgerror_resume_count = 0 branch; W fails; live Resume restores
writes). SuppressedErrorLeavesGateUndisturbed converted: suppressed
and soft-unstored errors still wake nothing (tail now lands a real
append failure instead of a synthetic error).

Neuter: disable the phase-2 re-publish (if (false && ...)):
SuppressedWalAppendErrorStillStopsDb hangs -- W parks forever on the
pinned range with no error, and the fixture watchdog aborts with "a
write never returned".

Q2 -- Close wakes every parked writer [N-2-4]

Property: when shutdown begins, every parked gate returns promptly: OK
if covered, else ShutdownInProgress (the stalled-write status). No
thread is inside WaitForWalDurability when DBImpl frees the gate's
cv/mutex. Close() does not hang. Writes concurrent with Close()
remain unsupported; whether a ShutdownInProgress write survives reopen
is decided by recovery's prefix rule -- observed below: W's landed
record replays and Get finds it.

How: SignalWalDurabilityWaitersOnShutdown sets
wal_durability_shutdown_ + epoch bump + SignalAll (gate mutex only,
a leaf). CancelAllBackgroundWork and CloseHelper call it;
CloseHelper then drains wal_durability_waiters_ without mutex_
(a woken waiter takes mutex_ to exit; the shutdown leg needs nothing
else, so the drain always terminates). Lock order is unchanged: the
waiter holds gate and mutex_ in disjoint scopes (leaf rule);
CloseHelper follows the established mutex_-above-gate order. New
TEST_SYNC_POINT("DBImpl::CloseHelper:GateWaitersDrained") after the
drain (unconditional; the CFHandleCleanup points sit in a conditional
block).

Evidence: CloseWakesParkedGateWithShutdown (W returns
ShutdownInProgress, Close returns, A lands OK, 0 waiters at the drain),
CloseWakesParkedGateWithSoftErrorSet (same with a stored compaction
NoSpace error), CloseWakesParkedGateWithFailedRangeStored (same in
the GC08 background-error state: retryable failure above W's target at
max_bgerror_resume_count = 0; reopen replays A and W, not F's
status). TSan + ASan clean (see test plan).

Neuter: drop the CloseHelper signal: W is not returned at 30 s and
CloseWakesParkedGateWithShutdown fails (W returns OK only after A
lands instead of ShutdownInProgress at Close).

Q3 -- A gate-failed write is never exposed [N-2-5, D-1]

Property: a write that returns a gate error because a lower WAL range
failed is never visible afterwards: not via Get/iterators/snapshots,
not in any SST, not via GetUpdatesSince -- after Resume(), after
auto-resume, after a clean reopen with the error set, and after a crash
reopen. Every acknowledged write below the failure stays present.
Sequences consumed by failed writes are not reissued (N=1 file-scoped
recovery already reserves failed_wal_sequence; kept across
partitions).

How: recovery computes flush_seqno_cutoff_ = min(failed low) - 1
before ResumeImpl's atomic flush; SeqnoCutoffIterator in
flush_job.cc hides everything above it (data, range tombstones), and
the dropped immutables purge removes the fenced memtable entries, so a
flush already running when the error lands cannot persist B either
(it either finished below the failure or its output is dropped with
the immutables). Every OK confirms under mutex_ with taint checked
first.

Evidence: GateFailedWriteAbsentAfterManualResume and
GateFailedWriteAbsentAfterAutoResume (N=2, B appends/inserts above
A's failed retryable file-scope append; B errors; after Resume Get(B)
is NotFound, no live SST contains B's key, writes resume; reopen keeps
acknowledged keys, never B). Crash leg with fault injection: not run
(see Not done); reopen legs cover the same recovery path. Landed
failed record: out of scope under D-1 (no device marker);
DISABLED_CrashAfterLandedFailedAppendRecoversNoFailedWrite kept as
is.

Neuter: GetFlushSeqnoCutoff() returns kMaxSequenceNumber always: B
is visible via Get, found in a live SST, and present after reopen
(3 failures in GateFailedWriteAbsentAfterManualResume).

Q4 -- Only N=1 failures fail a parked gate [N-7-1, F013, D-N71(b)]

Property: a parked write fails only when its target can never be
reached (failed WAL range at/below it) or on shutdown. Every other
background error -- soft or hard, flush/compaction/MANIFEST/async-open
-- reparks it; it returns OK once covered, as at N=1. New writes still
fail at PreprocessWrite exactly as at N=1. Non-outcome wakes repark
on the wake epoch, never spin.

How: the park loop's error leg reads GetBGError() but fails the
waiter only if failed_wal_ranges_ holds a range with low <= target
(else it re-arms on wal_durability_wake_epoch_ and reparks).
SignalWalDurabilityWaitersOnBGError still fires on every publication.

Evidence: SoftErrorDoesNotFailParkedGate (stored compaction NoSpace:
W stays parked, returns OK after A lands; new write succeeds; N=1 leg
identical), LeadershipSyncFailureWakesParkedGate (failed range above
W's target: repark, then OK), CompactionErrorWakesParkedGate (hard
compaction error: W returns OK after A lands, new write fails).
Converted to real append failures per Invariant 4 (all added by
e3fad05/D123701876; none deleted):
DurabilityWaitErrorBeforeAdvanceFailsWaiter,
DurabilityWaitAdvanceRacesError, CheckThenParkRaceWakesWaiter,
CompactionErrorWakesParkedGate,
GatePostWaitSyncFailureWakesParkedGate (a post-wait sync failure
records no failed range -- the record exists, only the fsync failed --
so W reparks on its wake and fails on M's later append failure),
LeadershipSyncFailureWakesParkedGate,
SuppressedErrorLeavesGateUndisturbed (tail only).

Neuter: fail on any stored error (if (true)): W returns the soft
error in SoftErrorDoesNotFailParkedGate (w_returned true, waiters 0,
w_status NOK).

Q5 -- Nothing above a released range succeeds [N-2-5/D-1]

Property: a write whose WAL record lies above a failed range never
returns OK whenever it reaches its gate. It fails with Aborted naming
the released range.

How: ClearWalDurabilityBGError taints (failed_high, max_allocated] into tainted_seq_intervals_ (DB lifetime) before
releasing each range; every gate (fast path and park loop) checks
TaintedTargetError first under mutex_. Fresh sequences always
exceed the recorded bound, so later writes never match.

Evidence: WriteAboveFailedRangeFailsAfterRelease (B stalled between
queue exit and gate entry via WriteThread::ExitAsBatchGroupLeader: BeforeGate, A fails below, auto-resume completes, B released: B
returns Aborted, absent after Resume and reopen, later writes OK).

Neuter: skip the taint push: B sees its target covered and returns OK
(IsAborted() false).

Q6 -- File-scoped live resume at N>1 [G-15 residual, (b)]

Property: (b) -- the upstream rejection of file-scoped WAL recovery
under MANIFEST tracking is lifted at N>1 only. After a file-scoped
failure on partition p, Resume() succeeds, the failed WAL retires
with consistent tracking records, acknowledged writes stay, the failed
write stays absent.

Why the upstream reason does not apply at N>1: upstream refuses
because file-scoped recovery abandons the failed WAL while MANIFEST
tracking still attests it. At N>1 recovery's atomic flush emits
DeleteWalsBefore past the failed WAL before retirement deletes any
file; SyncWAL cannot re-record a retired WAL (the recovery cutoff
skips it until popped); the non-MANIFEST predecessor mode is rejected
at N>1 at Open. So the tracking records stay consistent by
construction. Ported from D127099968 (pwal/ab/gc08-muse-D127099968
6e4892ce4b67) only the ResumeImpl wal_tracking_unsupported
N>1-only condition, per the allowed-prior-work clause; nothing else
from that diff (no Q7 clamp, no write_thread.cc mutex, no WBWI
release, no Q3 crash test).

Evidence: WalFileScopeErrorResumeRestoresWrites (N=1 leg still
refuses with NotSupported; N=2 leg: file-scoped failure on partition
1 after a rotate+sync seeded real tracking entries; Resume() OK;
failed WAL retired; reopen in all four recovery modes clean, no
"Missing WAL"/size mismatch; acknowledged present, failed absent;
crash-like reopen after resume replays the same state).
FileScopedFailureStaysStoppedAsAtOnePartition replaced (the Q6(b)
explicit allowance).

Neuter: restore the upstream rejection (drop the NumWalPartitions() == 1 condition): N=2 Resume() returns NotSupported and the test
fails there.

Fold-back split

Blame at the base (git blame 99157290e8e3; owning D-number from each
commit's footer revision line). New code goes to the diff
whose purpose it serves; upstream lines likewise.

  • Q1 -> D123701876: db/error_handler.{h,cc}
    is_wal_append_failure override (new lines; context e3fad05 +
    upstream); db/db_impl/db_impl_write.cc WALIOStatusCheck phase-2
    re-publish (GC08 winner lines + upstream);
    HandleMemTableInsertFailure signature + both WriteImpl call sites
    (upstream);
    db/db_impl/wal_durability_tracker.h IsOutstanding (new).
    Tests: SuppressedWalAppendErrorStillStopsDb,
    SuppressedRetryableErrorWithoutAutoRecovery (new);
    SuppressedErrorLeavesGateUndisturbed conversion (added by
    e3fad05).
  • Q2 -> D123551605: WaitForWalDurability shutdown leg (8019b1d
    lines); CancelAllBackgroundWork/CloseHelper signal + waiter
    drain + GateWaitersDrained point (new in upstream functions);
    db_impl.h decls (new). Tests: the 3 CloseWakesParkedGate*
    (new).
  • Q3 -> D123701876 + D123551605: db/column_family.h cutoff +
    db/flush_job.cc SeqnoCutoffIterator + db_impl.cc Resume
    cutoff/purge (new in upstream code -> D123701876, the resume owner
    under D-1); confirm_covered taint-first (gate exit, 8019b1d ->
    D123551605). Tests: the 2 GateFailedWriteAbsentAfter* (new ->
    D123701876).
  • Q4 -> D123551605 + D123701876: gate error leg + wake epoch +
    SignalWalDurabilityWaitersOnBGError body (8019b1d ->
    D123551605); error_handler.cc wake conditions (e3fad05 ->
    D123701876). Tests: SoftErrorDoesNotFailParkedGate (new ->
    D123551605, covers the gate exit); the 7 conversions (all added by
    e3fad05 -> D123701876).
  • Q5 -> D123701876 + D123551605: taint record in
    ClearWalDurabilityBGError (GC08 winner lines -> D123701876);
    TaintedTargetError + gate checks (new + gate -> D123551605);
    db/write_thread.cc BeforeGate point (new, upstream context ->
    D123551605). Test: WriteAboveFailedRangeFailsAfterRelease (new,
    GC08 fixture -> D123701876).
  • Q6 -> D123701876: ResumeImpl wal_tracking_unsupported lift
    (upstream lines, resume-under-D-1 purpose); test
    WalFileScopeErrorResumeRestoresWrites (replaces
    FileScopedFailureStaysStoppedAsAtOnePartition).
  • No hunk needs an off-map target: every hunk compiles at its mapped
    diff (new code only uses names its target already has).

Assumptions

  • D-N71 (b): dispatcher's cell blank -> Recommended (AB §4).
  • Venue: the notes commit (df307fab71a5) moved GC09 to the GitHub
    fork after dispatch; the doc's own commit-wins rule makes
    pwal/gc08 @ 99157290e8e3 the base (verified: SHA + 36-count).
  • Model name muse (branch pwal/gc09-muse, subject [Muse][GC])
    per Lane B history (AB §4: match the lane's naming).
  • Close() with a stored non-retryable non-fatal error waits at
    ReadyForShutdown upstream; tests Resume/clear before Close (AB
    §4: do not change upstream semantics to suit tests).
  • A post-wait sync failure records no failed WAL range (the record
    exists; only the fsync failed), so under (b) it reparks rather
    than fails (AB §4: (b)'s "can never be reached" test).
  • Tainted gates fail with Aborted naming the range (Q5 allows "the
    background error (or a dedicated status)").
  • Taint intervals are DB-lifetime; growth is bounded by the number of
    recoveries (AB §4: simplest correct).

Not done

  • Q3 fault-injection crash leg (FaultInjectionTestFS instead of
    Resume): not run. The Resume/auto-resume/reopen legs cover the same
    recovery code; the 180 s blackbox crash suite passes. The D-1
    landed-record case stays out of scope (disabled test kept as is).
  • Nothing else open: Q1, Q2, Q4, Q5, Q6 complete with evidence and
    neuters.

Cites D-1 (writer/DECISIONS.md) and closes G-13, N-2-4, N-2-5, N-7-1
(+F013), plus the GC08 carry-over (Q5, Q6). Still open: G-18, G-19,
N-3-1, N-3-2, G-11.

Test plan

Built and run with make in the fork (DEBUG_LEVEL=1 unless noted).
clang-format 21.1.2 (== upstream CI pin).

  • make db_write_test && ./db_write_test: 284/284 pass.
  • make db_wal_test && ./db_wal_test: 2074/2074 pass.
  • make error_handler_fs_test && ./error_handler_fs_test: 75/75.
  • make db_basic_test && ./db_basic_test: 300/300.
  • make db_log_iter_test && ./db_log_iter_test: 12/12.
  • make transaction_test && ./transaction_test: 3109/3109.
  • TSan (COMPILE_WITH_TSAN=1, own clone): all 10 new + 7 converted
    tests pass functionally; TSan emits the pre-existing
    destroyed-test-mutex artifact (constexpr stack std::mutex + stack
    address reuse under this toolchain's TSan) identically on the
    unpatched base (verified: base GatePostWait... and untouched
    PublicationBoundedForParallelGroup warn the same way). No warning
    implicates changed production lines or the shutdown lock order
    (audited: waiter holds gate/mutex_ disjointly; Close follows
    mutex_-above-gate). Buck2 TSan (fbcode//mode/dbg-tsan) on the
    content-identical tree: all new/converted tests pass with zero
    warnings.
  • ASan+UBSan (COMPILE_WITH_ASAN=1 COMPILE_WITH_UBSAN=1, own clone):
    all 10 new tests (incl. the 3 Q2 shutdown tests) + 19
    DBWalAppendFailureTest pass, zero sanitizer errors.
  • --gtest_repeat=100 on all 10 new + 9 converted/related
    SyncPoint/fault tests: 0 failed iterations each (19/19).
  • N=1 byte identity (DEBUG_LEVEL=0 db_bench at base and at this
    commit, fillseq --num=10000 --seed=20260928, 1 thread,
    --disable_auto_compactions=1): indexing off
    6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09
    both; indexing on
    9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796
    both (also equal to the historical buck values).
  • Blackbox crash 180 s (db_stress from this commit,
    --partition_wal_usage=partition_by_column_family --wal_partitions=1): "Crash-recovery verification passed".
  • make check-sources: pass. make check-format: pass (after
    format-diff.sh -y; re-ran new tests post-format: 19/19 + 24/24).
  • Neuters (scratch clone, one-line each, all observed): Q1 W never
    returns (watchdog abort); Q2 W not returned at 30 s; Q3 B exposed
    in Get/SST/reopen; Q4 W fails on soft error; Q5 B returns OK; Q6
    N=2 Resume NotSupported.

[GC] GC09: completion-gate liveness under D-1 and D-N71(b)

Reviewer question: at `wal_partitions > 1`, can any listener-suppressed
append error, shutdown, soft background error, or released failed range
leave a parked writer hanging, failing when N=1 would succeed, or
succeeding with data above a hole? Check the five places that answer it:
the suppression override in `WALIOStatusCheck`/`HandleKnownErrors`, the
shutdown leg and waiter drain in `CloseHelper`, the failed-range-only
error leg in `WaitForWalDurability`, the flush cutoff plus taint in
`ResumeImpl`/`ClearWalDurabilityBGError`, and the N>1-only tracking
lift in `ResumeImpl`.

D-N71: (b) (dispatcher blank, Recommended). A parked gate fails only on
a failed WAL range at or below its target, on taint from a released
range, or on shutdown; every other background error reparks it.

Gate exits (Q1-Q4 together):

| Condition | Outcome |
|---|---|
| Frontier covers target, no taint | OK |
| Failed WAL range at/below target | Stored background error |
| Target inside a tainted interval | Aborted (names the released range) |
| Shutdown, target uncovered | ShutdownInProgress |
| Any other stored background error | Repark; OK once covered |

## Q1 -- Suppressed WAL append errors still stop the DB [G-13]

Property: at N>1 a WAL append failure whose record never landed ends in
the background-error state with its N=1 severity even when a listener
suppresses it; listeners are still notified; suppression of
non-append errors and all N=1 suppression is unchanged.

How: two-phase. `HandleKnownErrors` takes `is_wal_append_failure` and
ignores the listener's override only for true append-misses; the
round-12/12.1 `>` guard is untouched. `WALIOStatusCheck` publishes
normally, then, only if suppressed (`GetBGError().ok()`) and the range
is still `IsOutstanding` on the tracker, re-publishes with the flag
set. A failure after the record landed (sync) leaves nothing pinned,
so its suppression stands. `HandleMemTableInsertFailure` records the
failed applied range at both call sites so an insert failure pins its
gates the same way.

Evidence: `SuppressedWalAppendErrorStillStopsDb` (N=2, listener
suppresses, non-file-scope non-retryable IOError; W fails bounded,
`GetBGError()` NOK; recovery via point-in-time reopen, the GC08 path),
`SuppressedRetryableErrorWithoutAutoRecovery`
(`max_bgerror_resume_count = 0` branch; W fails; live Resume restores
writes). `SuppressedErrorLeavesGateUndisturbed` converted: suppressed
and soft-unstored errors still wake nothing (tail now lands a real
append failure instead of a synthetic error).

Neuter: disable the phase-2 re-publish (`if (false && ...)`):
`SuppressedWalAppendErrorStillStopsDb` hangs -- W parks forever on the
pinned range with no error, and the fixture watchdog aborts with "a
write never returned".

## Q2 -- Close wakes every parked writer [N-2-4]

Property: when shutdown begins, every parked gate returns promptly: OK
if covered, else `ShutdownInProgress` (the stalled-write status). No
thread is inside `WaitForWalDurability` when DBImpl frees the gate's
cv/mutex. `Close()` does not hang. Writes concurrent with `Close()`
remain unsupported; whether a ShutdownInProgress write survives reopen
is decided by recovery's prefix rule -- observed below: W's landed
record replays and `Get` finds it.

How: `SignalWalDurabilityWaitersOnShutdown` sets
`wal_durability_shutdown_` + epoch bump + `SignalAll` (gate mutex only,
a leaf). `CancelAllBackgroundWork` and `CloseHelper` call it;
`CloseHelper` then drains `wal_durability_waiters_` without `mutex_`
(a woken waiter takes `mutex_` to exit; the shutdown leg needs nothing
else, so the drain always terminates). Lock order is unchanged: the
waiter holds gate and `mutex_` in disjoint scopes (leaf rule);
`CloseHelper` follows the established `mutex_`-above-gate order. New
`TEST_SYNC_POINT("DBImpl::CloseHelper:GateWaitersDrained")` after the
drain (unconditional; the CFHandleCleanup points sit in a conditional
block).

Evidence: `CloseWakesParkedGateWithShutdown` (W returns
ShutdownInProgress, Close returns, A lands OK, 0 waiters at the drain),
`CloseWakesParkedGateWithSoftErrorSet` (same with a stored compaction
NoSpace error), `CloseWakesParkedGateWithFailedRangeStored` (same in
the GC08 background-error state: retryable failure above W's target at
`max_bgerror_resume_count = 0`; reopen replays A and W, not F's
status). TSan + ASan clean (see test plan).

Neuter: drop the `CloseHelper` signal: W is not returned at 30 s and
`CloseWakesParkedGateWithShutdown` fails (W returns OK only after A
lands instead of ShutdownInProgress at Close).

## Q3 -- A gate-failed write is never exposed [N-2-5, D-1]

Property: a write that returns a gate error because a lower WAL range
failed is never visible afterwards: not via `Get`/iterators/snapshots,
not in any SST, not via `GetUpdatesSince` -- after `Resume()`, after
auto-resume, after a clean reopen with the error set, and after a crash
reopen. Every acknowledged write below the failure stays present.
Sequences consumed by failed writes are not reissued (N=1 file-scoped
recovery already reserves `failed_wal_sequence`; kept across
partitions).

How: recovery computes `flush_seqno_cutoff_ = min(failed low) - 1`
before `ResumeImpl`'s atomic flush; `SeqnoCutoffIterator` in
`flush_job.cc` hides everything above it (data, range tombstones), and
the dropped immutables purge removes the fenced memtable entries, so a
flush already running when the error lands cannot persist B either
(it either finished below the failure or its output is dropped with
the immutables). Every OK confirms under `mutex_` with taint checked
first.

Evidence: `GateFailedWriteAbsentAfterManualResume` and
`GateFailedWriteAbsentAfterAutoResume` (N=2, B appends/inserts above
A's failed retryable file-scope append; B errors; after Resume `Get(B)`
is NotFound, no live SST contains B's key, writes resume; reopen keeps
acknowledged keys, never B). Crash leg with fault injection: not run
(see Not done); reopen legs cover the same recovery path. Landed
failed record: out of scope under D-1 (no device marker);
`DISABLED_CrashAfterLandedFailedAppendRecoversNoFailedWrite` kept as
is.

Neuter: `GetFlushSeqnoCutoff()` returns `kMaxSequenceNumber` always: B
is visible via `Get`, found in a live SST, and present after reopen
(3 failures in `GateFailedWriteAbsentAfterManualResume`).

## Q4 -- Only N=1 failures fail a parked gate [N-7-1, F013, D-N71(b)]

Property: a parked write fails only when its target can never be
reached (failed WAL range at/below it) or on shutdown. Every other
background error -- soft or hard, flush/compaction/MANIFEST/async-open
-- reparks it; it returns OK once covered, as at N=1. New writes still
fail at `PreprocessWrite` exactly as at N=1. Non-outcome wakes repark
on the wake epoch, never spin.

How: the park loop's error leg reads `GetBGError()` but fails the
waiter only if `failed_wal_ranges_` holds a range with `low <= target`
(else it re-arms on `wal_durability_wake_epoch_` and reparks).
`SignalWalDurabilityWaitersOnBGError` still fires on every publication.

Evidence: `SoftErrorDoesNotFailParkedGate` (stored compaction NoSpace:
W stays parked, returns OK after A lands; new write succeeds; N=1 leg
identical), `LeadershipSyncFailureWakesParkedGate` (failed range above
W's target: repark, then OK), `CompactionErrorWakesParkedGate` (hard
compaction error: W returns OK after A lands, new write fails).
Converted to real append failures per Invariant 4 (all added by
e3fad05/D123701876; none deleted):
`DurabilityWaitErrorBeforeAdvanceFailsWaiter`,
`DurabilityWaitAdvanceRacesError`, `CheckThenParkRaceWakesWaiter`,
`CompactionErrorWakesParkedGate`,
`GatePostWaitSyncFailureWakesParkedGate` (a post-wait sync failure
records no failed range -- the record exists, only the fsync failed --
so W reparks on its wake and fails on M's later append failure),
`LeadershipSyncFailureWakesParkedGate`,
`SuppressedErrorLeavesGateUndisturbed` (tail only).

Neuter: fail on any stored error (`if (true)`): W returns the soft
error in `SoftErrorDoesNotFailParkedGate` (w_returned true, waiters 0,
w_status NOK).

## Q5 -- Nothing above a released range succeeds [N-2-5/D-1]

Property: a write whose WAL record lies above a failed range never
returns OK whenever it reaches its gate. It fails with Aborted naming
the released range.

How: `ClearWalDurabilityBGError` taints `(failed_high,
max_allocated]` into `tainted_seq_intervals_` (DB lifetime) before
releasing each range; every gate (fast path and park loop) checks
`TaintedTargetError` first under `mutex_`. Fresh sequences always
exceed the recorded bound, so later writes never match.

Evidence: `WriteAboveFailedRangeFailsAfterRelease` (B stalled between
queue exit and gate entry via `WriteThread::ExitAsBatchGroupLeader:
BeforeGate`, A fails below, auto-resume completes, B released: B
returns Aborted, absent after Resume and reopen, later writes OK).

Neuter: skip the taint push: B sees its target covered and returns OK
(`IsAborted()` false).

## Q6 -- File-scoped live resume at N>1 [G-15 residual, (b)]

Property: (b) -- the upstream rejection of file-scoped WAL recovery
under MANIFEST tracking is lifted at N>1 only. After a file-scoped
failure on partition p, `Resume()` succeeds, the failed WAL retires
with consistent tracking records, acknowledged writes stay, the failed
write stays absent.

Why the upstream reason does not apply at N>1: upstream refuses
because file-scoped recovery abandons the failed WAL while MANIFEST
tracking still attests it. At N>1 recovery's atomic flush emits
`DeleteWalsBefore` past the failed WAL before retirement deletes any
file; `SyncWAL` cannot re-record a retired WAL (the recovery cutoff
skips it until popped); the non-MANIFEST predecessor mode is rejected
at N>1 at Open. So the tracking records stay consistent by
construction. Ported from D127099968 (`pwal/ab/gc08-muse-D127099968`
`6e4892ce4b67`) only the `ResumeImpl` `wal_tracking_unsupported`
N>1-only condition, per the allowed-prior-work clause; nothing else
from that diff (no Q7 clamp, no `write_thread.cc` mutex, no WBWI
release, no Q3 crash test).

Evidence: `WalFileScopeErrorResumeRestoresWrites` (N=1 leg still
refuses with NotSupported; N=2 leg: file-scoped failure on partition
1 after a rotate+sync seeded real tracking entries; `Resume()` OK;
failed WAL retired; reopen in all four recovery modes clean, no
"Missing WAL"/size mismatch; acknowledged present, failed absent;
crash-like reopen after resume replays the same state).
`FileScopedFailureStaysStoppedAsAtOnePartition` replaced (the Q6(b)
explicit allowance).

Neuter: restore the upstream rejection (drop the `NumWalPartitions()
== 1` condition): N=2 `Resume()` returns NotSupported and the test
fails there.

## Fold-back split

Blame at the base (`git blame 9915729`; owning D-number from each
commit's footer revision line). New code goes to the diff
whose purpose it serves; upstream lines likewise.

- Q1 -> D123701876: `db/error_handler.{h,cc}`
  `is_wal_append_failure` override (new lines; context e3fad05 +
  upstream); `db/db_impl/db_impl_write.cc` `WALIOStatusCheck` phase-2
  re-publish (GC08 winner lines + upstream);
  `HandleMemTableInsertFailure` signature + both `WriteImpl` call sites
  (upstream);
  `db/db_impl/wal_durability_tracker.h` `IsOutstanding` (new).
  Tests: `SuppressedWalAppendErrorStillStopsDb`,
  `SuppressedRetryableErrorWithoutAutoRecovery` (new);
  `SuppressedErrorLeavesGateUndisturbed` conversion (added by
  e3fad05).
- Q2 -> D123551605: `WaitForWalDurability` shutdown leg (8019b1d
  lines); `CancelAllBackgroundWork`/`CloseHelper` signal + waiter
  drain + `GateWaitersDrained` point (new in upstream functions);
  `db_impl.h` decls (new). Tests: the 3 `CloseWakesParkedGate*`
  (new).
- Q3 -> D123701876 + D123551605: `db/column_family.h` cutoff +
  `db/flush_job.cc` `SeqnoCutoffIterator` + `db_impl.cc` Resume
  cutoff/purge (new in upstream code -> D123701876, the resume owner
  under D-1); `confirm_covered` taint-first (gate exit, 8019b1d ->
  D123551605). Tests: the 2 `GateFailedWriteAbsentAfter*` (new ->
  D123701876).
- Q4 -> D123551605 + D123701876: gate error leg + wake epoch +
  `SignalWalDurabilityWaitersOnBGError` body (8019b1d ->
  D123551605); `error_handler.cc` wake conditions (e3fad05 ->
  D123701876). Tests: `SoftErrorDoesNotFailParkedGate` (new ->
  D123551605, covers the gate exit); the 7 conversions (all added by
  e3fad05 -> D123701876).
- Q5 -> D123701876 + D123551605: taint record in
  `ClearWalDurabilityBGError` (GC08 winner lines -> D123701876);
  `TaintedTargetError` + gate checks (new + gate -> D123551605);
  `db/write_thread.cc` `BeforeGate` point (new, upstream context ->
  D123551605). Test: `WriteAboveFailedRangeFailsAfterRelease` (new,
  GC08 fixture -> D123701876).
- Q6 -> D123701876: `ResumeImpl` `wal_tracking_unsupported` lift
  (upstream lines, resume-under-D-1 purpose); test
  `WalFileScopeErrorResumeRestoresWrites` (replaces
  `FileScopedFailureStaysStoppedAsAtOnePartition`).
- No hunk needs an off-map target: every hunk compiles at its mapped
  diff (new code only uses names its target already has).

## Assumptions

- D-N71 (b): dispatcher's cell blank -> Recommended (AB §4).
- Venue: the notes commit (`df307fab71a5`) moved GC09 to the GitHub
  fork after dispatch; the doc's own commit-wins rule makes
  `pwal/gc08 @ 9915729` the base (verified: SHA + 36-count).
- Model name `muse` (branch `pwal/gc09-muse`, subject `[Muse][GC]`)
  per Lane B history (AB §4: match the lane's naming).
- `Close()` with a stored non-retryable non-fatal error waits at
  `ReadyForShutdown` upstream; tests Resume/clear before Close (AB
  §4: do not change upstream semantics to suit tests).
- A post-wait sync failure records no failed WAL range (the record
  exists; only the fsync failed), so under (b) it reparks rather
  than fails (AB §4: (b)'s "can never be reached" test).
- Tainted gates fail with Aborted naming the range (Q5 allows "the
  background error (or a dedicated status)").
- Taint intervals are DB-lifetime; growth is bounded by the number of
  recoveries (AB §4: simplest correct).

## Not done

- Q3 fault-injection crash leg (`FaultInjectionTestFS` instead of
  Resume): not run. The Resume/auto-resume/reopen legs cover the same
  recovery code; the 180 s blackbox crash suite passes. The D-1
  landed-record case stays out of scope (disabled test kept as is).
- Nothing else open: Q1, Q2, Q4, Q5, Q6 complete with evidence and
  neuters.

Cites D-1 (`writer/DECISIONS.md`) and closes G-13, N-2-4, N-2-5, N-7-1
(+F013), plus the GC08 carry-over (Q5, Q6). Still open: G-18, G-19,
N-3-1, N-3-2, G-11.

## Test plan

Built and run with `make` in the fork (`DEBUG_LEVEL=1` unless noted).
clang-format 21.1.2 (== upstream CI pin).

- `make db_write_test && ./db_write_test`: 284/284 pass.
- `make db_wal_test && ./db_wal_test`: 2074/2074 pass.
- `make error_handler_fs_test && ./error_handler_fs_test`: 75/75.
- `make db_basic_test && ./db_basic_test`: 300/300.
- `make db_log_iter_test && ./db_log_iter_test`: 12/12.
- `make transaction_test && ./transaction_test`: 3109/3109.
- TSan (`COMPILE_WITH_TSAN=1`, own clone): all 10 new + 7 converted
  tests pass functionally; TSan emits the pre-existing
  destroyed-test-mutex artifact (constexpr stack `std::mutex` + stack
  address reuse under this toolchain's TSan) identically on the
  unpatched base (verified: base `GatePostWait...` and untouched
  `PublicationBoundedForParallelGroup` warn the same way). No warning
  implicates changed production lines or the shutdown lock order
  (audited: waiter holds gate/`mutex_` disjointly; Close follows
  `mutex_`-above-gate). Buck2 TSan (`fbcode//mode/dbg-tsan`) on the
  content-identical tree: all new/converted tests pass with zero
  warnings.
- ASan+UBSan (`COMPILE_WITH_ASAN=1 COMPILE_WITH_UBSAN=1`, own clone):
  all 10 new tests (incl. the 3 Q2 shutdown tests) + 19
  `DBWalAppendFailureTest` pass, zero sanitizer errors.
- `--gtest_repeat=100` on all 10 new + 9 converted/related
  SyncPoint/fault tests: 0 failed iterations each (19/19).
- N=1 byte identity (`DEBUG_LEVEL=0 db_bench` at base and at this
  commit, `fillseq --num=10000 --seed=20260928`, 1 thread,
  `--disable_auto_compactions=1`): indexing off
  `6d1351117a289a2784449a68d5421b1aa385ab0b383273c2c5918befa9181b09`
  both; indexing on
  `9a69a3fc66777fadce05e8a999479a5f57364aca27cd6d22aa00e4631adfc796`
  both (also equal to the historical buck values).
- Blackbox crash 180 s (`db_stress` from this commit,
  `--partition_wal_usage=partition_by_column_family
  --wal_partitions=1`): "Crash-recovery verification passed".
- `make check-sources`: pass. `make check-format`: pass (after
  `format-diff.sh -y`; re-ran new tests post-format: 19/19 + 24/24).
- Neuters (scratch clone, one-line each, all observed): Q1 W never
  returns (watchdog abort); Q2 W not returned at 30 s; Q3 B exposed
  in Get/SST/reopen; Q4 W fails on soft error; Q5 B returns OK; Q6
  N=2 Resume NotSupported.
@JustinGaoF

Copy link
Copy Markdown
Owner Author

GC09 A/B round: the other candidate (Claude, Phabricator D127204780) was accepted. Closing this one; the branch is kept as allowed prior work.

@JustinGaoF JustinGaoF closed this Oct 24, 2026
JustinGaoF added a commit that referenced this pull request Nov 19, 2026
Summary:
Teaches the log layer to encode and decode WAL index records. The writer does not allocate indexes; it receives one per record from the caller (allocation arrives in the next diff, together with the sequence number).

Writer. `SetPartitionWALUsage` turns indexing on for a writer before its first record and never changes afterwards, so a file's records are either all indexed or none are. `WALIndexEnabled(PartitionWALUsage)` is an allowlist switch with no default, so a future enum value fails the build until it is classified. `MaybeAddWALIndexMarkerRecord` emits the leading marker. The marker carries no payload and consumes no index; its value is positional: as the first record, it makes an older binary fail on record #1 rather than partway through replay.

`AddRecord` takes the assigned `wal_index`, encodes it as a fixed64 ahead of the record, and picks the indexed record type via `SelectRecordType`. The index is part of the payload for checksum and fragmentation, so it survives both. With indexing enabled, a zero or non-increasing index fails the write with `Corruption` in every build; `kWALIndexStartNumber = 1` and zero means "no index". Non-decreasing sequence numbers per writer are checked by a debug assert. On the uncompressed path the index goes to `EmitPhysicalRecord` as a separate 8-byte prefix, so the caller's payload is never copied; compression still needs one contiguous buffer and keeps the joined copy. On-disk bytes, record boundaries and checksums are identical either way. `EmitPhysicalRecord` selects the header size via `IsRecyclableRecordType`; with indexing off the output is byte-identical to before, which a `static_assert` in the tests pins by comparing the predicate against the old whitelist for every pre-existing type.

One hazard is documented rather than fixed here: an index allocated for an append that fails is burned. The `TODO` in `AddRecord` names the two remedies.

Reader. `log::Reader` and `FragmentBufferedReader` decode indexed records through `MaybeStripAndVerifyWALIndex`, which moves the leading fixed64 into `last_read_wal_index_`, strips it, and recomputes the logical-record checksum over the stripped payload, so upper layers see the same bytes and checksum as without indexing. A record whose type claims an index but whose payload is shorter than 8 bytes is reported as corruption; a record without an index clears the value, so `GetLastReadWALIndex()` always describes the record just returned (zero when none).

Decoding is driven only by the record type at every dispatch site in both readers, so a file can mix indexed and plain records. The marker is not needed to decode anything; it is only checked for position: a marker after a data record, or one that interrupts a fragmented record, is reported and the partial record is dropped (`Reader` also resets its streaming checksum), so both readers reject the same input. Fragments of one logical record that disagree about carrying an index are reported. `ReadPhysicalRecord` selects the header size via `IsRecyclableRecordType`.

There is deliberately no gap or continuity check. `wal_index` is consecutive across all WAL files of the DB, not within one file, so a jump between successive records in a file is normal; treating it as a gap would be a false positive whose response is truncation.

Test Plan:
New `LogTest` cases in `db/log_test.cc`, parameterised over recycling x retry-read so both `Reader` and `FragmentBufferedReader` are covered:
- Writer: `WALIndexMarkerRecordIsEmpty`, `WALIndexAssignedConsecutively`, `WALIndexValuesCanSpanWriters`, `WALIndexMissingAssignmentFailsWrite`, `WALIndexNonIncreasingFailsWrite`, `WALIndexNotAssignedWhenDisabled`, and the `HeaderSelectionUnchangedForPreWALIndexTypes` `static_assert`.
- Round trip and layout: `WALIndexReadWrite`, `WALIndexDisabledStaysVanilla`, `WALIndexRecordsDoNotRequireMarker`, `WALIndexMixedWithPlainRecords`, `WALIndexLargeValueRoundTrips`, `WALIndexLargeRecord`, `WALIndexFirstFragmentByteLayout`, `WALIndexEmptyRecordByteLayout`, `WALIndexStraddlesBlockBoundary`, `WALIndexConsecutiveAcrossFilesInPartition`, `WALIndexNonConsecutiveWithinFileIsAccepted`.
- Corruption: `WALIndexTooShortRecordReportsCorruption`, `WALIndexInconsistentFragmentTypesReportsCorruption`, `WALIndexInconsistentMiddleFragmentDropsRecord`, `WALIndexInconsistentLastFragmentDropsRecord`, `WALIndexMarkerAfterDataRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordAfterFirstRecord`.

```
make -j32 log_test && ./log_test --gtest_filter='*WALIndex*'
./log_test
make check-sources
```

Results: per-group gate results are added after validation.
JustinGaoF added a commit that referenced this pull request Nov 19, 2026
Summary:
Teaches the log layer to encode and decode WAL index records. The writer does not allocate indexes; it receives one per record from the caller (allocation arrives in the next diff, together with the sequence number).

Writer. `SetPartitionWALUsage` turns indexing on for a writer before its first record and never changes afterwards, so a file's records are either all indexed or none are. `WALIndexEnabled(PartitionWALUsage)` is an allowlist switch with no default, so a future enum value fails the build until it is classified. `MaybeAddWALIndexMarkerRecord` emits the leading marker. The marker carries no payload and consumes no index; its value is positional: as the first record, it makes an older binary fail on record #1 rather than partway through replay.

`AddRecord` takes the assigned `wal_index`, encodes it as a fixed64 ahead of the record, and picks the indexed record type via `SelectRecordType`. The index is part of the payload for checksum and fragmentation, so it survives both. With indexing enabled, a zero or non-increasing index fails the write with `Corruption` in every build; `kWALIndexStartNumber = 1` and zero means "no index". Non-decreasing sequence numbers per writer are checked by a debug assert. On the uncompressed path the index goes to `EmitPhysicalRecord` as a separate 8-byte prefix, so the caller's payload is never copied; compression still needs one contiguous buffer and keeps the joined copy. On-disk bytes, record boundaries and checksums are identical either way. `EmitPhysicalRecord` selects the header size via `IsRecyclableRecordType`; with indexing off the output is byte-identical to before, which a `static_assert` in the tests pins by comparing the predicate against the old whitelist for every pre-existing type.

One hazard is documented rather than fixed here: an index allocated for an append that fails is burned. The `TODO` in `AddRecord` names the two remedies.

Reader. `log::Reader` and `FragmentBufferedReader` decode indexed records through `MaybeStripAndVerifyWALIndex`, which moves the leading fixed64 into `last_read_wal_index_`, strips it, and recomputes the logical-record checksum over the stripped payload, so upper layers see the same bytes and checksum as without indexing. A record whose type claims an index but whose payload is shorter than 8 bytes is reported as corruption; a record without an index clears the value, so `GetLastReadWALIndex()` always describes the record just returned (zero when none).

Decoding is driven only by the record type at every dispatch site in both readers, so a file can mix indexed and plain records. The marker is not needed to decode anything; it is only checked for position: a marker after a data record, or one that interrupts a fragmented record, is reported and the partial record is dropped (`Reader` also resets its streaming checksum), so both readers reject the same input. Fragments of one logical record that disagree about carrying an index are reported. `ReadPhysicalRecord` selects the header size via `IsRecyclableRecordType`.

There is deliberately no gap or continuity check. `wal_index` is consecutive across all WAL files of the DB, not within one file, so a jump between successive records in a file is normal; treating it as a gap would be a false positive whose response is truncation.

Test Plan:
New `LogTest` cases in `db/log_test.cc`, parameterised over recycling x retry-read so both `Reader` and `FragmentBufferedReader` are covered:
- Writer: `WALIndexMarkerRecordIsEmpty`, `WALIndexAssignedConsecutively`, `WALIndexValuesCanSpanWriters`, `WALIndexMissingAssignmentFailsWrite`, `WALIndexNonIncreasingFailsWrite`, `WALIndexNotAssignedWhenDisabled`, and the `HeaderSelectionUnchangedForPreWALIndexTypes` `static_assert`.
- Round trip and layout: `WALIndexReadWrite`, `WALIndexDisabledStaysVanilla`, `WALIndexRecordsDoNotRequireMarker`, `WALIndexMixedWithPlainRecords`, `WALIndexLargeValueRoundTrips`, `WALIndexLargeRecord`, `WALIndexFirstFragmentByteLayout`, `WALIndexEmptyRecordByteLayout`, `WALIndexStraddlesBlockBoundary`, `WALIndexConsecutiveAcrossFilesInPartition`, `WALIndexNonConsecutiveWithinFileIsAccepted`.
- Corruption: `WALIndexTooShortRecordReportsCorruption`, `WALIndexInconsistentFragmentTypesReportsCorruption`, `WALIndexInconsistentMiddleFragmentDropsRecord`, `WALIndexInconsistentLastFragmentDropsRecord`, `WALIndexMarkerAfterDataRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordAfterFirstRecord`.

```
make -j32 log_test && ./log_test --gtest_filter='*WALIndex*'
./log_test
make check-sources
```

Results: per-group gate results are added after validation.
JustinGaoF added a commit that referenced this pull request Nov 19, 2026
Summary:
Teaches the log layer to encode and decode WAL index records. The writer does not allocate indexes; it receives one per record from the caller (allocation arrives in the next diff, together with the sequence number).

Writer. `SetPartitionWALUsage` turns indexing on for a writer before its first record and never changes afterwards, so a file's records are either all indexed or none are. `WALIndexEnabled(PartitionWALUsage)` is an allowlist switch with no default, so a future enum value fails the build until it is classified. `MaybeAddWALIndexMarkerRecord` emits the leading marker. The marker carries no payload and consumes no index; its value is positional: as the first record, it makes an older binary fail on record #1 rather than partway through replay.

`AddRecord` takes the assigned `wal_index`, encodes it as a fixed64 ahead of the record, and picks the indexed record type via `SelectRecordType`. The index is part of the payload for checksum and fragmentation, so it survives both. With indexing enabled, a zero or non-increasing index fails the write with `Corruption` in every build; `kWALIndexStartNumber = 1` and zero means "no index". Non-decreasing sequence numbers per writer are checked by a debug assert. On the uncompressed path the index goes to `EmitPhysicalRecord` as a separate 8-byte prefix, so the caller's payload is never copied; compression still needs one contiguous buffer and keeps the joined copy. On-disk bytes, record boundaries and checksums are identical either way. `EmitPhysicalRecord` selects the header size via `IsRecyclableRecordType`; with indexing off the output is byte-identical to before, which a `static_assert` in the tests pins by comparing the predicate against the old whitelist for every pre-existing type.

One hazard is documented rather than fixed here: an index allocated for an append that fails is burned. The `TODO` in `AddRecord` names the two remedies.

Reader. `log::Reader` and `FragmentBufferedReader` decode indexed records through `MaybeStripAndVerifyWALIndex`, which moves the leading fixed64 into `last_read_wal_index_`, strips it, and recomputes the logical-record checksum over the stripped payload, so upper layers see the same bytes and checksum as without indexing. A record whose type claims an index but whose payload is shorter than 8 bytes is reported as corruption; a record without an index clears the value, so `GetLastReadWALIndex()` always describes the record just returned (zero when none).

Decoding is driven only by the record type at every dispatch site in both readers, so a file can mix indexed and plain records. The marker is not needed to decode anything; it is only checked for position: a marker after a data record, or one that interrupts a fragmented record, is reported and the partial record is dropped (`Reader` also resets its streaming checksum), so both readers reject the same input. Fragments of one logical record that disagree about carrying an index are reported. `ReadPhysicalRecord` selects the header size via `IsRecyclableRecordType`.

There is deliberately no gap or continuity check. `wal_index` is consecutive across all WAL files of the DB, not within one file, so a jump between successive records in a file is normal; treating it as a gap would be a false positive whose response is truncation.

Test Plan:
New `LogTest` cases in `db/log_test.cc`, parameterised over recycling x retry-read so both `Reader` and `FragmentBufferedReader` are covered:
- Writer: `WALIndexMarkerRecordIsEmpty`, `WALIndexAssignedConsecutively`, `WALIndexValuesCanSpanWriters`, `WALIndexMissingAssignmentFailsWrite`, `WALIndexNonIncreasingFailsWrite`, `WALIndexNotAssignedWhenDisabled`, and the `HeaderSelectionUnchangedForPreWALIndexTypes` `static_assert`.
- Round trip and layout: `WALIndexReadWrite`, `WALIndexDisabledStaysVanilla`, `WALIndexRecordsDoNotRequireMarker`, `WALIndexMixedWithPlainRecords`, `WALIndexLargeValueRoundTrips`, `WALIndexLargeRecord`, `WALIndexFirstFragmentByteLayout`, `WALIndexEmptyRecordByteLayout`, `WALIndexStraddlesBlockBoundary`, `WALIndexConsecutiveAcrossFilesInPartition`, `WALIndexNonConsecutiveWithinFileIsAccepted`.
- Corruption: `WALIndexTooShortRecordReportsCorruption`, `WALIndexInconsistentFragmentTypesReportsCorruption`, `WALIndexInconsistentMiddleFragmentDropsRecord`, `WALIndexInconsistentLastFragmentDropsRecord`, `WALIndexMarkerAfterDataRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordAfterFirstRecord`.

```
make -j32 log_test && ./log_test --gtest_filter='*WALIndex*'
./log_test
make check-sources
```

Results: per-group gate results are added after validation.
JustinGaoF added a commit that referenced this pull request Nov 19, 2026
Summary:
Teaches the log layer to encode and decode WAL index records. The writer does not allocate indexes; it receives one per record from the caller (allocation arrives in the next diff, together with the sequence number).

Writer. `SetPartitionWALUsage` turns indexing on for a writer before its first record and never changes afterwards, so a file's records are either all indexed or none are. `WALIndexEnabled(PartitionWALUsage)` is an allowlist switch with no default, so a future enum value fails the build until it is classified. `MaybeAddWALIndexMarkerRecord` emits the leading marker. The marker carries no payload and consumes no index; its value is positional: as the first record, it makes an older binary fail on record #1 rather than partway through replay.

`AddRecord` takes the assigned `wal_index`, encodes it as a fixed64 ahead of the record, and picks the indexed record type via `SelectRecordType`. The index is part of the payload for checksum and fragmentation, so it survives both. With indexing enabled, a zero or non-increasing index fails the write with `Corruption` in every build; `kWALIndexStartNumber = 1` and zero means "no index". Non-decreasing sequence numbers per writer are checked by a debug assert. On the uncompressed path the index goes to `EmitPhysicalRecord` as a separate 8-byte prefix, so the caller's payload is never copied; compression still needs one contiguous buffer and keeps the joined copy. On-disk bytes, record boundaries and checksums are identical either way. `EmitPhysicalRecord` selects the header size via `IsRecyclableRecordType`; with indexing off the output is byte-identical to before, which a `static_assert` in the tests pins by comparing the predicate against the old whitelist for every pre-existing type.

One hazard is documented rather than fixed here: an index allocated for an append that fails is burned. The `TODO` in `AddRecord` names the two remedies.

Reader. `log::Reader` and `FragmentBufferedReader` decode indexed records through `MaybeStripAndVerifyWALIndex`, which moves the leading fixed64 into `last_read_wal_index_`, strips it, and recomputes the logical-record checksum over the stripped payload, so upper layers see the same bytes and checksum as without indexing. A record whose type claims an index but whose payload is shorter than 8 bytes is reported as corruption; a record without an index clears the value, so `GetLastReadWALIndex()` always describes the record just returned (zero when none).

Decoding is driven only by the record type at every dispatch site in both readers, so a file can mix indexed and plain records. The marker is not needed to decode anything; it is only checked for position: a marker after a data record, or one that interrupts a fragmented record, is reported and the partial record is dropped (`Reader` also resets its streaming checksum), so both readers reject the same input. Fragments of one logical record that disagree about carrying an index are reported. `ReadPhysicalRecord` selects the header size via `IsRecyclableRecordType`.

There is deliberately no gap or continuity check. `wal_index` is consecutive across all WAL files of the DB, not within one file, so a jump between successive records in a file is normal; treating it as a gap would be a false positive whose response is truncation.

Test Plan:
New `LogTest` cases in `db/log_test.cc`, parameterised over recycling x retry-read so both `Reader` and `FragmentBufferedReader` are covered:
- Writer: `WALIndexMarkerRecordIsEmpty`, `WALIndexAssignedConsecutively`, `WALIndexValuesCanSpanWriters`, `WALIndexMissingAssignmentFailsWrite`, `WALIndexNonIncreasingFailsWrite`, `WALIndexNotAssignedWhenDisabled`, and the `HeaderSelectionUnchangedForPreWALIndexTypes` `static_assert`.
- Round trip and layout: `WALIndexReadWrite`, `WALIndexDisabledStaysVanilla`, `WALIndexRecordsDoNotRequireMarker`, `WALIndexMixedWithPlainRecords`, `WALIndexLargeValueRoundTrips`, `WALIndexLargeRecord`, `WALIndexFirstFragmentByteLayout`, `WALIndexEmptyRecordByteLayout`, `WALIndexStraddlesBlockBoundary`, `WALIndexConsecutiveAcrossFilesInPartition`, `WALIndexNonConsecutiveWithinFileIsAccepted`.
- Corruption: `WALIndexTooShortRecordReportsCorruption`, `WALIndexInconsistentFragmentTypesReportsCorruption`, `WALIndexInconsistentMiddleFragmentDropsRecord`, `WALIndexInconsistentLastFragmentDropsRecord`, `WALIndexMarkerAfterDataRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordAfterFirstRecord`.

```
make -j32 log_test && ./log_test --gtest_filter='*WALIndex*'
./log_test
make check-sources
```

Results: per-group gate results are added after validation.
JustinGaoF added a commit that referenced this pull request Nov 19, 2026
Summary:
Teaches the log layer to encode and decode WAL index records. The writer does not allocate indexes; it receives one per record from the caller (allocation arrives in the next diff, together with the sequence number).

Writer. `SetPartitionWALUsage` turns indexing on for a writer before its first record and never changes afterwards, so a file's records are either all indexed or none are. `WALIndexEnabled(PartitionWALUsage)` is an allowlist switch with no default, so a future enum value fails the build until it is classified. `MaybeAddWALIndexMarkerRecord` emits the leading marker. The marker carries no payload and consumes no index; its value is positional: as the first record, it makes an older binary fail on record #1 rather than partway through replay.

`AddRecord` takes the assigned `wal_index`, encodes it as a fixed64 ahead of the record, and picks the indexed record type via `SelectRecordType`. The index is part of the payload for checksum and fragmentation, so it survives both. With indexing enabled, a zero or non-increasing index fails the write with `Corruption` in every build; `kWALIndexStartNumber = 1` and zero means "no index". Non-decreasing sequence numbers per writer are checked by a debug assert. On the uncompressed path the index goes to `EmitPhysicalRecord` as a separate 8-byte prefix, so the caller's payload is never copied; compression still needs one contiguous buffer and keeps the joined copy. On-disk bytes, record boundaries and checksums are identical either way. `EmitPhysicalRecord` selects the header size via `IsRecyclableRecordType`; with indexing off the output is byte-identical to before, which a `static_assert` in the tests pins by comparing the predicate against the old whitelist for every pre-existing type.

One hazard is documented rather than fixed here: an index allocated for an append that fails is burned. The `TODO` in `AddRecord` names the two remedies.

Reader. `log::Reader` and `FragmentBufferedReader` decode indexed records through `MaybeStripAndVerifyWALIndex`, which moves the leading fixed64 into `last_read_wal_index_`, strips it, and recomputes the logical-record checksum over the stripped payload, so upper layers see the same bytes and checksum as without indexing. A record whose type claims an index but whose payload is shorter than 8 bytes is reported as corruption; a record without an index clears the value, so `GetLastReadWALIndex()` always describes the record just returned (zero when none).

Decoding is driven only by the record type at every dispatch site in both readers, so a file can mix indexed and plain records. The marker is not needed to decode anything; it is only checked for position: a marker after a data record, or one that interrupts a fragmented record, is reported and the partial record is dropped (`Reader` also resets its streaming checksum), so both readers reject the same input. Fragments of one logical record that disagree about carrying an index are reported. `ReadPhysicalRecord` selects the header size via `IsRecyclableRecordType`.

There is deliberately no gap or continuity check. `wal_index` is consecutive across all WAL files of the DB, not within one file, so a jump between successive records in a file is normal; treating it as a gap would be a false positive whose response is truncation.

Test Plan:
New `LogTest` cases in `db/log_test.cc`, parameterised over recycling x retry-read so both `Reader` and `FragmentBufferedReader` are covered:
- Writer: `WALIndexMarkerRecordIsEmpty`, `WALIndexAssignedConsecutively`, `WALIndexValuesCanSpanWriters`, `WALIndexMissingAssignmentFailsWrite`, `WALIndexNonIncreasingFailsWrite`, `WALIndexNotAssignedWhenDisabled`, and the `HeaderSelectionUnchangedForPreWALIndexTypes` `static_assert`.
- Round trip and layout: `WALIndexReadWrite`, `WALIndexDisabledStaysVanilla`, `WALIndexRecordsDoNotRequireMarker`, `WALIndexMixedWithPlainRecords`, `WALIndexLargeValueRoundTrips`, `WALIndexLargeRecord`, `WALIndexFirstFragmentByteLayout`, `WALIndexEmptyRecordByteLayout`, `WALIndexStraddlesBlockBoundary`, `WALIndexConsecutiveAcrossFilesInPartition`, `WALIndexNonConsecutiveWithinFileIsAccepted`.
- Corruption: `WALIndexTooShortRecordReportsCorruption`, `WALIndexInconsistentFragmentTypesReportsCorruption`, `WALIndexInconsistentMiddleFragmentDropsRecord`, `WALIndexInconsistentLastFragmentDropsRecord`, `WALIndexMarkerAfterDataRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordAfterFirstRecord`.

```
make -j32 log_test && ./log_test --gtest_filter='*WALIndex*'
./log_test
make check-sources
```

Results: per-group gate results are added after validation.
JustinGaoF added a commit that referenced this pull request Nov 19, 2026
Summary:
Pull Request resolved: meta#15220

Adds the WAL index record types to the log format. Header-only; no writer, reader or on-disk change yet.

Marker types `kWALIndexMarkerType` (12) and `kRecyclableWALIndexMarkerType` (13) tag a file as carrying per-record ordering numbers. Indexed data record types `kWALIndexFullType`..`kRecyclableWALIndexLastType` (14-21) mirror the existing full/first/middle/last set, with a recyclable twin for each, so every existing record shape has an indexed counterpart. Each fragment is self-describing: the marker is not required to decode a record, and the marker itself carries no payload.

Also adds `IsWALIndexRecordType` and a new `IsRecyclableRecordType` predicate (the existing recyclable types plus the new recyclable marker and indexed types, replacing hand-written checks in the writer and readers in the diffs above), and defines `kWALIndexSize = 8` for the fixed64 prefix.

All new types stay below `kRecordTypeSafeIgnoreMask`, so an older binary reports an indexed record as an unknown type instead of silently skipping it. The report fails Open only in the strict recovery modes. Under point-in-time or skip recovery the older binary stops replaying that file and opens without its records. A `static_assert` naming all ten WAL index types enforces that, so renumbering any of them into the ignorable range breaks the build instead of turning into silent data loss.

M1: Absorbs GC04 log_format.h parts (marker comment, 'reports on record #1', safe-ignore paragraph; 2-line guard sentence stays in S-A).

Test Plan:
Header-only change; covered by the consumers in the diffs above and by compile-time assertions here.

- The `static_assert` on `kRecordTypeSafeIgnoreMask` names every one of the ten WAL index types, so renumbering any of them into the safe-ignore range fails the build. An earlier revision asserted only two of the ten; the other eight were unguarded.
- `buck2 run fbcode//internal_repo_rocksdb/repo:log_test` at this diff — 211 tests pass.
- `arc lint -a fbcode/internal_repo_rocksdb/repo/db/log_format.h` — no issues.

Formatting verified per file rather than asserted: `clang-format <file> | diff - <file>` is empty for every changed file, using the repo-pinned `tools/third-party/clang-format/clang-format`.

M1: doc-only; tip suites 7870/0.
M1 re-verification (2026-10-20, after rebasing the stack onto master f0c3a35689fc and clang-formatting): per-diff gate at this diff passed (CI format check, `rocksdb_lib` build, touched test targets); tip suites 8126/0; N=1 byte identity equals T0.

M3 B.1 at this diff (clang-format 21.1.2 on its changed lines, make check-sources, debug librocksdb build; no test file touched): PASS.

Reviewers: rajivharlalka, kinbertchou, taopeng, rbanerjee2, jkangs, anand76, huixiao

Subscribers: jewoongh, taopeng, rbanerjee2, anand76, huixiao, jkangs

Differential Revision: https://phabricator.intern.facebook.com/D118369740
JustinGaoF added a commit that referenced this pull request Nov 19, 2026
Summary:
Pull Request resolved: meta#15221

Teaches `log::Writer` to emit WAL index records. The writer does not allocate the index — it receives one from the caller and encodes it. Allocation lands in a later diff, where the sequence number is also assigned.

`SetPartitionWALUsage` turns indexing on for a writer; `WALIndexEnabled` reports it. `MaybeAddWALIndexMarkerRecord` emits the leading marker. The marker carries **no payload** — the record type alone identifies the file, and its value is positional: it is the first record, so an older binary fails on record #1 rather than partway through replay.

`AddRecord` takes the assigned `wal_index`, encodes it as a fixed64 ahead of the record, and picks the matching indexed record type via `SelectRecordType`. Because the index counts as part of the record's payload for checksum and fragmentation, it survives both. With indexing enabled, a zero or non-increasing index fails the write with `Corruption` in every build. Non-decreasing sequence numbers per writer are checked only by a debug assert.

The uncompressed path passes the index to `EmitPhysicalRecord` as a **separate 8-byte prefix**, so the caller's payload is never copied. Compression still requires one contiguous input, so that path keeps the joined buffer. `wal_compression` defaults to `kNoCompression`, so the common path avoids the allocation and the full write-batch copy. On-disk bytes, record boundaries and checksums are identical either way.

`EmitPhysicalRecord` now selects the header size via `IsRecyclableRecordType` rather than a hand-maintained whitelist. With indexing disabled the output is byte-identical to before, and a `static_assert` in the tests pins that by checking the new predicate agrees with the old whitelist on every pre-existing record type.

One hazard is documented rather than fixed: a failed append burns an allocated index. Harmless until a completeness check exists; the `TODO` names the two remedies.

Measured on the no-copy path, with the full stack applied so `db_bench` can drive it — `--benchmarks=fillseq --partition_wal_usage=wal_index_single_file --wal_compression=none --compression_type=none --disable_auto_compactions=true --threads=1`, medians of 3 runs on one AMD EPYC-Genoa host, ~512 MiB written per run. `wal_index_single_file` is an earlier spelling of what is now `partition_by_column_family` and no longer parses; the numbers were not re-measured:

| Value size | Entries | Copying prefix | Separate prefix | Latency change |
| 64 KiB | 8,192 | 224.908 us/op, 4,445 ops/s | 215.764 us/op, 4,628 ops/s | -4.1% |
| 1 MiB | 512 | 2,813.432 us/op, 355 ops/s | 2,373.035 us/op, 421 ops/s | -15.7% |

Test Plan:
Writer-side tests in `db/log_test.cc`, parameterised over recycling x retry-read. They assert on raw file bytes, since nothing above this diff can read an indexed record yet:

- `WALIndexMarkerRecordIsEmpty` — marker is first, right type, zero payload length.
- `WALIndexAssignedConsecutively` — four records encode the four indices they were handed.
- `WALIndexValuesCanSpanWriters` — two writers encode indices drawn from one external sequence.
- `WALIndexMissingAssignmentFailsWrite` — indexing enabled with no assigned index is rejected.
- `WALIndexNonIncreasingFailsWrite` -- an index not above the previous one is rejected with `Corruption`.
- `static_assert(HeaderSelectionUnchangedForPreWALIndexTypes())` — compile-time proof that header selection is unchanged for every pre-existing record type.

Byte-layout and round-trip coverage of the separate-prefix encoding (first-fragment layout, empty record, an index straddling a block boundary) lives in the reader diff above, where a reader exists to complete the round trip.

```
$ buck2 run fbcode//internal_repo_rocksdb/repo:log_test
[==========] 227 tests from 4 test suites ran.
[  PASSED  ] 227 tests.
```

`arc lint -a` on `log_writer.cc`, `log_writer.h`, `log_test.cc` — no issues.

Formatting verified per file rather than asserted: `clang-format <file> | diff - <file>` is empty for every changed file, using the repo-pinned `tools/third-party/clang-format/clang-format`.

M3 B.1 at this diff (clang-format 21.1.2 on its changed lines, make check-sources, debug build, touched test binaries): PASS; log_test: 231 pass.

Reviewers: rajivharlalka, huixiao, dyao, kinbertchou, taopeng, xbw, generatedunixname1816288208882371

Subscribers: jewoongh, rbanerjee2, anand76

Differential Revision: https://phabricator.intern.facebook.com/D118369607
JustinGaoF added a commit that referenced this pull request Nov 19, 2026
Summary:
Teaches the log layer to encode and decode WAL index records. The writer does not allocate indexes; it receives one per record from the caller (allocation arrives in the next diff, together with the sequence number).

Writer. `SetPartitionWALUsage` turns indexing on for a writer before its first record and never changes afterwards, so a file's records are either all indexed or none are. `WALIndexEnabled(PartitionWALUsage)` is an allowlist switch with no default, so a future enum value fails the build until it is classified. `MaybeAddWALIndexMarkerRecord` emits the leading marker. The marker carries no payload and consumes no index; its value is positional: as the first record, it makes an older binary fail on record #1 rather than partway through replay.

`AddRecord` takes the assigned `wal_index`, encodes it as a fixed64 ahead of the record, and picks the indexed record type via `SelectRecordType`. The index is part of the payload for checksum and fragmentation, so it survives both. With indexing enabled, a zero or non-increasing index fails the write with `Corruption` in every build; `kWALIndexStartNumber = 1` and zero means "no index". Non-decreasing sequence numbers per writer are checked by a debug assert. On the uncompressed path the index goes to `EmitPhysicalRecord` as a separate 8-byte prefix, so the caller's payload is never copied; compression still needs one contiguous buffer and keeps the joined copy. On-disk bytes, record boundaries and checksums are identical either way. `EmitPhysicalRecord` selects the header size via `IsRecyclableRecordType`; with indexing off the output is byte-identical to before, which a `static_assert` in the tests pins by comparing the predicate against the old whitelist for every pre-existing type.

One hazard is documented rather than fixed here: an index allocated for an append that fails is burned. The `TODO` in `AddRecord` names the two remedies.

Reader. `log::Reader` and `FragmentBufferedReader` decode indexed records through `MaybeStripAndVerifyWALIndex`, which moves the leading fixed64 into `last_read_wal_index_`, strips it, and recomputes the logical-record checksum over the stripped payload, so upper layers see the same bytes and checksum as without indexing. A record whose type claims an index but whose payload is shorter than 8 bytes is reported as corruption; a record without an index clears the value, so `GetLastReadWALIndex()` always describes the record just returned (zero when none).

Decoding is driven only by the record type at every dispatch site in both readers, so a file can mix indexed and plain records. The marker is not needed to decode anything; it is only checked for position: a marker after a data record, or one that interrupts a fragmented record, is reported and the partial record is dropped (`Reader` also resets its streaming checksum), so both readers reject the same input. Fragments of one logical record that disagree about carrying an index are reported. `ReadPhysicalRecord` selects the header size via `IsRecyclableRecordType`.

There is deliberately no gap or continuity check. `wal_index` is consecutive across all WAL files of the DB, not within one file, so a jump between successive records in a file is normal; treating it as a gap would be a false positive whose response is truncation.

Test Plan:
New `LogTest` cases in `db/log_test.cc`, parameterised over recycling x retry-read so both `Reader` and `FragmentBufferedReader` are covered:
- Writer: `WALIndexMarkerRecordIsEmpty`, `WALIndexAssignedConsecutively`, `WALIndexValuesCanSpanWriters`, `WALIndexMissingAssignmentFailsWrite`, `WALIndexNonIncreasingFailsWrite`, `WALIndexNotAssignedWhenDisabled`, and the `HeaderSelectionUnchangedForPreWALIndexTypes` `static_assert`.
- Round trip and layout: `WALIndexReadWrite`, `WALIndexDisabledStaysVanilla`, `WALIndexRecordsDoNotRequireMarker`, `WALIndexMixedWithPlainRecords`, `WALIndexLargeValueRoundTrips`, `WALIndexLargeRecord`, `WALIndexFirstFragmentByteLayout`, `WALIndexEmptyRecordByteLayout`, `WALIndexStraddlesBlockBoundary`, `WALIndexConsecutiveAcrossFilesInPartition`, `WALIndexNonConsecutiveWithinFileIsAccepted`.
- Corruption: `WALIndexTooShortRecordReportsCorruption`, `WALIndexInconsistentFragmentTypesReportsCorruption`, `WALIndexInconsistentMiddleFragmentDropsRecord`, `WALIndexInconsistentLastFragmentDropsRecord`, `WALIndexMarkerAfterDataRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordAfterFirstRecord`.

```
make -j32 log_test && ./log_test --gtest_filter='*WALIndex*'
./log_test
make check-sources
```

Results: per-group gate results are added after validation.
JustinGaoF added a commit that referenced this pull request Nov 19, 2026
Summary:
Teaches the log layer to encode and decode WAL index records. The writer does not allocate indexes; it receives one per record from the caller (allocation arrives in the next diff, together with the sequence number).

Writer. `SetPartitionWALUsage` turns indexing on for a writer before its first record and never changes afterwards, so a file's records are either all indexed or none are. `WALIndexEnabled(PartitionWALUsage)` is an allowlist switch with no default, so a future enum value fails the build until it is classified. `MaybeAddWALIndexMarkerRecord` emits the leading marker. The marker carries no payload and consumes no index; its value is positional: as the first record, it makes an older binary fail on record #1 rather than partway through replay.

`AddRecord` takes the assigned `wal_index`, encodes it as a fixed64 ahead of the record, and picks the indexed record type via `SelectRecordType`. The index is part of the payload for checksum and fragmentation, so it survives both. With indexing enabled, a zero or non-increasing index fails the write with `Corruption` in every build; `kWALIndexStartNumber = 1` and zero means "no index". Non-decreasing sequence numbers per writer are checked by a debug assert. On the uncompressed path the index goes to `EmitPhysicalRecord` as a separate 8-byte prefix, so the caller's payload is never copied; compression still needs one contiguous buffer and keeps the joined copy. On-disk bytes, record boundaries and checksums are identical either way. `EmitPhysicalRecord` selects the header size via `IsRecyclableRecordType`; with indexing off the output is byte-identical to before, which a `static_assert` in the tests pins by comparing the predicate against the old whitelist for every pre-existing type.

One hazard is documented rather than fixed here: an index allocated for an append that fails is burned. The `TODO` in `AddRecord` names the two remedies.

Reader. `log::Reader` and `FragmentBufferedReader` decode indexed records through `MaybeStripAndVerifyWALIndex`, which moves the leading fixed64 into `last_read_wal_index_`, strips it, and recomputes the logical-record checksum over the stripped payload, so upper layers see the same bytes and checksum as without indexing. A record whose type claims an index but whose payload is shorter than 8 bytes is reported as corruption; a record without an index clears the value, so `GetLastReadWALIndex()` always describes the record just returned (zero when none).

Decoding is driven only by the record type at every dispatch site in both readers, so a file can mix indexed and plain records. The marker is not needed to decode anything; it is only checked for position: a marker after a data record, or one that interrupts a fragmented record, is reported and the partial record is dropped (`Reader` also resets its streaming checksum), so both readers reject the same input. Fragments of one logical record that disagree about carrying an index are reported. `ReadPhysicalRecord` selects the header size via `IsRecyclableRecordType`.

There is deliberately no gap or continuity check. `wal_index` is consecutive across all WAL files of the DB, not within one file, so a jump between successive records in a file is normal; treating it as a gap would be a false positive whose response is truncation.

Test Plan:
New `LogTest` cases in `db/log_test.cc`, parameterised over recycling x retry-read so both `Reader` and `FragmentBufferedReader` are covered:
- Writer: `WALIndexMarkerRecordIsEmpty`, `WALIndexAssignedConsecutively`, `WALIndexValuesCanSpanWriters`, `WALIndexMissingAssignmentFailsWrite`, `WALIndexNonIncreasingFailsWrite`, `WALIndexNotAssignedWhenDisabled`, and the `HeaderSelectionUnchangedForPreWALIndexTypes` `static_assert`.
- Round trip and layout: `WALIndexReadWrite`, `WALIndexDisabledStaysVanilla`, `WALIndexRecordsDoNotRequireMarker`, `WALIndexMixedWithPlainRecords`, `WALIndexLargeValueRoundTrips`, `WALIndexLargeRecord`, `WALIndexFirstFragmentByteLayout`, `WALIndexEmptyRecordByteLayout`, `WALIndexStraddlesBlockBoundary`, `WALIndexConsecutiveAcrossFilesInPartition`, `WALIndexNonConsecutiveWithinFileIsAccepted`.
- Corruption: `WALIndexTooShortRecordReportsCorruption`, `WALIndexInconsistentFragmentTypesReportsCorruption`, `WALIndexInconsistentMiddleFragmentDropsRecord`, `WALIndexInconsistentLastFragmentDropsRecord`, `WALIndexMarkerAfterDataRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordAfterFirstRecord`.

```
make -j32 log_test && ./log_test --gtest_filter='*WALIndex*'
./log_test
make check-sources
```

Results: per-group gate results are added after validation.
JustinGaoF added a commit that referenced this pull request Nov 20, 2026
Summary:
Teaches the log layer to encode and decode WAL index records. The writer does not allocate indexes; it receives one per record from the caller (allocation arrives in the next diff, together with the sequence number).

Writer. `SetPartitionWALUsage` turns indexing on for a writer before its first record and never changes afterwards, so a file's records are either all indexed or none are. `WALIndexEnabled(PartitionWALUsage)` is an allowlist switch with no default, so a future enum value fails the build until it is classified. `MaybeAddWALIndexMarkerRecord` emits the leading marker. The marker carries no payload and consumes no index; its value is positional: as the first record, it makes an older binary fail on record #1 rather than partway through replay.

`AddRecord` takes the assigned `wal_index`, encodes it as a fixed64 ahead of the record, and picks the indexed record type via `SelectRecordType`. The index is part of the payload for checksum and fragmentation, so it survives both. With indexing enabled, a zero or non-increasing index fails the write with `Corruption` in every build; `kWALIndexStartNumber = 1` and zero means "no index". Non-decreasing sequence numbers per writer are checked by a debug assert. On the uncompressed path the index goes to `EmitPhysicalRecord` as a separate 8-byte prefix, so the caller's payload is never copied; compression still needs one contiguous buffer and keeps the joined copy. On-disk bytes, record boundaries and checksums are identical either way. `EmitPhysicalRecord` selects the header size via `IsRecyclableRecordType`; with indexing off the output is byte-identical to before, which a `static_assert` in the tests pins by comparing the predicate against the old whitelist for every pre-existing type.

One hazard is documented rather than fixed here: an index allocated for an append that fails is burned. The `TODO` in `AddRecord` names the two remedies.

Reader. `log::Reader` and `FragmentBufferedReader` decode indexed records through `MaybeStripAndVerifyWALIndex`, which moves the leading fixed64 into `last_read_wal_index_`, strips it, and recomputes the logical-record checksum over the stripped payload, so upper layers see the same bytes and checksum as without indexing. A record whose type claims an index but whose payload is shorter than 8 bytes is reported as corruption; a record without an index clears the value, so `GetLastReadWALIndex()` always describes the record just returned (zero when none).

Decoding is driven only by the record type at every dispatch site in both readers, so a file can mix indexed and plain records. The marker is not needed to decode anything; it is only checked for position: a marker after a data record, or one that interrupts a fragmented record, is reported and the partial record is dropped (`Reader` also resets its streaming checksum), so both readers reject the same input. Fragments of one logical record that disagree about carrying an index are reported. `ReadPhysicalRecord` selects the header size via `IsRecyclableRecordType`.

There is deliberately no gap or continuity check. `wal_index` is consecutive across all WAL files of the DB, not within one file, so a jump between successive records in a file is normal; treating it as a gap would be a false positive whose response is truncation.

Test Plan:
New `LogTest` cases in `db/log_test.cc`, parameterised over recycling x retry-read so both `Reader` and `FragmentBufferedReader` are covered:
- Writer: `WALIndexMarkerRecordIsEmpty`, `WALIndexAssignedConsecutively`, `WALIndexValuesCanSpanWriters`, `WALIndexMissingAssignmentFailsWrite`, `WALIndexNonIncreasingFailsWrite`, `WALIndexNotAssignedWhenDisabled`, and the `HeaderSelectionUnchangedForPreWALIndexTypes` `static_assert`.
- Round trip and layout: `WALIndexReadWrite`, `WALIndexDisabledStaysVanilla`, `WALIndexRecordsDoNotRequireMarker`, `WALIndexMixedWithPlainRecords`, `WALIndexLargeValueRoundTrips`, `WALIndexLargeRecord`, `WALIndexFirstFragmentByteLayout`, `WALIndexEmptyRecordByteLayout`, `WALIndexStraddlesBlockBoundary`, `WALIndexConsecutiveAcrossFilesInPartition`, `WALIndexNonConsecutiveWithinFileIsAccepted`.
- Corruption: `WALIndexTooShortRecordReportsCorruption`, `WALIndexInconsistentFragmentTypesReportsCorruption`, `WALIndexInconsistentMiddleFragmentDropsRecord`, `WALIndexInconsistentLastFragmentDropsRecord`, `WALIndexMarkerAfterDataRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordAfterFirstRecord`.

```
make -j32 log_test && ./log_test --gtest_filter='*WALIndex*'
./log_test
make check-sources
```

Results: per-group gate results are added after validation.
JustinGaoF added a commit that referenced this pull request Nov 22, 2026
Summary:
Teaches the log layer to encode and decode WAL index records. The writer does not allocate indexes; it receives one per record from the caller (allocation arrives in the next diff, together with the sequence number).

Writer. `SetPartitionWALUsage` turns indexing on for a writer before its first record and never changes afterwards, so a file's records are either all indexed or none are. `WALIndexEnabled(PartitionWALUsage)` is an allowlist switch with no default, so a future enum value fails the build until it is classified. `MaybeAddWALIndexMarkerRecord` emits the leading marker. The marker carries no payload and consumes no index; its value is positional: as the first record, it makes an older binary fail on record #1 rather than partway through replay.

`AddRecord` takes the assigned `wal_index`, encodes it as a fixed64 ahead of the record, and picks the indexed record type via `SelectRecordType`. The index is part of the payload for checksum and fragmentation, so it survives both. With indexing enabled, a zero or non-increasing index fails the write with `Corruption` in every build; `kWALIndexStartNumber = 1` and zero means "no index". Non-decreasing sequence numbers per writer are checked by a debug assert. On the uncompressed path the index goes to `EmitPhysicalRecord` as a separate 8-byte prefix, so the caller's payload is never copied; compression still needs one contiguous buffer and keeps the joined copy. On-disk bytes, record boundaries and checksums are identical either way. `EmitPhysicalRecord` selects the header size via `IsRecyclableRecordType`; with indexing off the output is byte-identical to before, which a `static_assert` in the tests pins by comparing the predicate against the old whitelist for every pre-existing type.

One hazard is documented rather than fixed here: an index allocated for an append that fails is burned. The `TODO` in `AddRecord` names the two remedies.

Reader. `log::Reader` and `FragmentBufferedReader` decode indexed records through `MaybeStripAndVerifyWALIndex`, which moves the leading fixed64 into `last_read_wal_index_`, strips it, and recomputes the logical-record checksum over the stripped payload, so upper layers see the same bytes and checksum as without indexing. A record whose type claims an index but whose payload is shorter than 8 bytes is reported as corruption; a record without an index clears the value, so `GetLastReadWALIndex()` always describes the record just returned (zero when none).

Decoding is driven only by the record type at every dispatch site in both readers, so a file can mix indexed and plain records. The marker is not needed to decode anything; it is only checked for position: a marker after a data record, or one that interrupts a fragmented record, is reported and the partial record is dropped (`Reader` also resets its streaming checksum), so both readers reject the same input. Fragments of one logical record that disagree about carrying an index are reported. `ReadPhysicalRecord` selects the header size via `IsRecyclableRecordType`.

There is deliberately no gap or continuity check. `wal_index` is consecutive across all WAL files of the DB, not within one file, so a jump between successive records in a file is normal; treating it as a gap would be a false positive whose response is truncation.

Test Plan:
New `LogTest` cases in `db/log_test.cc`, parameterised over recycling x retry-read so both `Reader` and `FragmentBufferedReader` are covered:
- Writer: `WALIndexMarkerRecordIsEmpty`, `WALIndexAssignedConsecutively`, `WALIndexValuesCanSpanWriters`, `WALIndexMissingAssignmentFailsWrite`, `WALIndexNonIncreasingFailsWrite`, `WALIndexNotAssignedWhenDisabled`, and the `HeaderSelectionUnchangedForPreWALIndexTypes` `static_assert`.
- Round trip and layout: `WALIndexReadWrite`, `WALIndexDisabledStaysVanilla`, `WALIndexRecordsDoNotRequireMarker`, `WALIndexMixedWithPlainRecords`, `WALIndexLargeValueRoundTrips`, `WALIndexLargeRecord`, `WALIndexFirstFragmentByteLayout`, `WALIndexEmptyRecordByteLayout`, `WALIndexStraddlesBlockBoundary`, `WALIndexConsecutiveAcrossFilesInPartition`, `WALIndexNonConsecutiveWithinFileIsAccepted`.
- Corruption: `WALIndexTooShortRecordReportsCorruption`, `WALIndexInconsistentFragmentTypesReportsCorruption`, `WALIndexInconsistentMiddleFragmentDropsRecord`, `WALIndexInconsistentLastFragmentDropsRecord`, `WALIndexMarkerAfterDataRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordReportsCorruption`, `WALIndexMarkerInsidePartialRecordAfterFirstRecord`.

```
make -j32 log_test && ./log_test --gtest_filter='*WALIndex*'
./log_test
make check-sources
```

Results: per-group gate results are added after validation.
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.

1 participant