Skip to content

#4872 Fix single-replica ledger autorecovery loop - #4873

Open
Radiancebobo wants to merge 2 commits into
apache:masterfrom
Radiancebobo:feature/skip-single-replica-ledgers-autorecovery
Open

Radiancebobo wants to merge 2 commits into
apache:masterfrom
Radiancebobo:feature/skip-single-replica-ledgers-autorecovery

Conversation

@Radiancebobo

Copy link
Copy Markdown

Skip failed-bookie recovery tasks for ledgers with writeQuorumSize=1, and clean up historical tasks without affecting placement-policy repairs.

Add dedicated metrics and regression tests for task filtering, lock release, normal recovery retries, and cleanup failures.

Fix #4872

Motivation

BookKeeper can create ledgers with writeQuorumSize=1. Every entry in such a
ledger has only one data source. If that Bookie is permanently lost, the
Auditor currently publishes an underreplication task, and the
ReplicationWorker repeatedly tries to read a source replica that cannot
exist. The retry loop consumes worker, client, and ZooKeeper resources and
creates noisy failure logs while obscuring ledgers that can actually be
recovered.

This change intentionally does not claim to recover or reconstruct lost data.
It stops an impossible automatic recovery path and exposes a dedicated metric
so operators can alert on the skipped condition and use backups or manual
recovery when data must be restored.

Changes

  • Filter failed-Bookie underreplication publication in
    AuditorTask.publishSuspectedLedgersAsync:
    • Read ledger metadata before creating the underreplication mark.
    • Skip ledgers whose metadata has writeQuorumSize == 1.
    • Keep metadata-read failures fail-open, so an unknown ledger is still
      marked for normal recovery.
    • Ignore the race where the ledger was deleted before publication.
    • Count and size only ledgers actually submitted to the underreplication
      manager.
  • Add NUM_SINGLE_REPLICA_LEDGERS_SKIPPED in the Auditor scope and log the
    ledger id, quorum size, reason, and action for skipped publications.
  • Add a consumer-side guard in ReplicationWorker for historical tasks that
    predate this change. After taking the task lock, a task is removed through
    markLedgerReplicated when writeQuorumSize == 1 and its replicaList is
    non-empty (the failed-Bookie task shape).
  • Preserve placement-policy repair tasks: a writeQuorumSize == 1 task with
    an empty replicaList continues through the existing replication path.
  • Represent SUCCESS, FAILED, and SKIPPED worker outcomes separately so
    historical cleanup is not counted as replication success or failure. Add
    NUM_SINGLE_REPLICA_UNDERREPLICATED_LEDGERS_SKIPPED for this path.
  • Add unit and integration coverage for single-replica filtering, deleted
    ledgers, fail-open metadata errors, published-ledger statistics, historical
    cleanup, placement-policy task preservation, and skipped-operation metrics.

Compatibility and operational notes

No configuration, ZooKeeper schema, protobuf field, or public API is added.
The behavior is deterministic from ledger metadata and applies on upgrade.
Existing underreplication znodes are persistent, so the Worker-side guard is
required to converge historical failed-Bookie tasks. Tasks with an empty
replicaList, unreadable metadata, or a concurrent znode version change are
not forcibly removed by the single-replica cleanup guard. If metadata is
unreadable, the Worker falls back to the normal recovery path; that path may
remove the task if recovery completes successfully.

The skipped counters are operational signals, not recovery-success counters:

  • auditor.NUM_SINGLE_REPLICA_LEDGERS_SKIPPED
  • replication_worker.NUM_SINGLE_REPLICA_UNDERREPLICATED_LEDGERS_SKIPPED

These counters are cumulative skip events, not a deduplicated count of unique
ledger IDs. The same ledger may be counted again during a later audit or retry.

Verification

Tests run on the branch:

mvn -pl bookkeeper-server -am -DskipTests=false \
  -Dtest='AuditorBookieCheckTaskTest,TestReplicationWorker' \
  -Dsurefire.failIfNoSpecifiedTests=false test

The command passes with 25 tests: 6 Auditor tests and 19 ReplicationWorker
tests. The full BookKeeper precommit command remains appropriate before merge:
mvn clean apache-rat:check install spotbugs:check.


In order to uphold a high standard for quality for code contributions, Apache BookKeeper runs various precommit
checks for pull requests. A pull request can only be merged when it passes precommit checks.


Be sure to do all the following to help us incorporate your contribution
quickly and easily:

Otherwise:

  • Make sure the PR title is formatted like:
    <Issue #>: Description of pull request
  • Replace <Issue #> in the title and #TODO above with the actual Issue number.
  • Add targeted regression and integration tests for the behavior change.
  • Run the full precommit command before merge: mvn clean apache-rat:check install spotbugs:check.

Skip failed-bookie recovery tasks for ledgers with writeQuorumSize=1,
and clean up historical tasks without affecting placement-policy repairs.

Add dedicated metrics and regression tests for task filtering, lock release,
normal recovery retries, and cleanup failures.
@StevenLuMT
StevenLuMT requested a lite review from Copilot September 10, 2026 01:28

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Warning

Copilot couldn't run its full agentic review because it didn't start before the timeout. Make sure your repository has a runner available, or add a copilot-code-review.yml file specifying one with the runs-on attribute. See the docs for more details.

Pull request overview

This PR prevents futile autorecovery loops for ledgers with writeQuorumSize=1 by skipping failed-bookie underreplication tasks (and cleaning up historical ones), while adding dedicated operational metrics and regression tests.

Changes:

  • Auditor: read ledger metadata before publishing underreplication tasks and skip failed-bookie tasks for writeQuorumSize==1 ledgers while keeping fail-open behavior on metadata errors.
  • ReplicationWorker: detect and clean up historical single-replica failed-bookie tasks without attempting replication, tracking a dedicated “skipped” outcome metric.
  • Tests & docs: add regression tests for the new filtering/cleanup behavior and document the operational meaning of the new counters.

Reviewed changes

Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
site3/website/docs/admin/autorecovery.md Documents skipped single-replica failed-bookie tasks and the new metrics.
bookkeeper-server/src/test/java/org/apache/bookkeeper/replication/TestReplicationWorker.java Adds worker regression tests for historical cleanup, placement-policy preservation, and metrics.
bookkeeper-server/src/test/java/org/apache/bookkeeper/replication/AuditorBookieCheckTaskTest.java Adds auditor regression tests for single-replica filtering, deleted ledgers, and fail-open behavior.
bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/ReplicationWorker.java Introduces “skipped” outcome handling and historical cleanup guard for single-replica tasks.
bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/ReplicationStats.java Adds new metric constants for auditor and worker skip counters.
bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/AuditorTask.java Implements metadata-based filtering and adjusts published-ledger stats to exclude skipped items.
bookkeeper-server/src/main/java/org/apache/bookkeeper/replication/AuditorStats.java Adds auditor counter for single-replica skip events.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@Radiancebobo

Copy link
Copy Markdown
Author

@StevenLuMT Could you please take a look at this PR when you have a moment? Your review is highly appreciated.

@hangc0276 hangc0276 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Adversarial review with scenario tests against head cb4ef67 (I ran AuditorBookieCheckTaskTest; I did not run TestReplicationWorker). The design is sound: a single-replica ledger has nothing to rebuild from, placement-policy tasks bypass the auditor skip, and a NoSuchLedger wrapped by a dependent stage is still recognised. I found two small issues, one test gap and one cost note, all inline.

underReplicatedSize.add(metadata.getValue().getLength());
}
}), null).whenComplete((res, e) -> {
ledgerId -> ledgerManager.readLedgerMetadata(ledgerId).handle((metadata, exception) -> {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: marking now depends on this metadata read completing. Before this PR the read only fed the size statistic and markLedgerUnderreplicatedAsync ran independently; now a ledger is only marked after its read future completes, and AuditorBookieCheckTask.auditBookies blocks on the combined future with FutureUtils.result(...) and no timeout. A read that never completes (rather than failing) leaves that ledger unmarked and the audit thread waiting.

Reproduced with a never-completing readLedgerMetadata future for one ledger: after 500 ms markLedgerUnderreplicatedAsync was never called (testAdvPendingMetadataReadDoesNotBlockMarking). The control with a completed read marks as expected. Real ZooKeeper failures complete the future with an error and are handled fail-open here, so this only matters for a read that never completes, and the mark call itself has the same exposure; this just adds one more call to the chain. A timeout on the read that falls back to the fail-open path (mark anyway) would keep the old liveness.

.attr("ledgerId", ledgerId)
.log("Ledger metadata was empty; publishing underreplicated mark fail-open");
} else if (metadata.getValue().getWriteQuorumSize() == 1) {
auditorStats.getNumSingleReplicaLedgersSkipped().inc();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: this counter counts (bookie, ledger) pairs rather than ledgers. AuditorBookieCheckTask.handleLostBookiesAsync calls publishSuspectedLedgersAsync once per lost bookie, so a writeQuorumSize=1 ledger striped over two failed bookies is read, skipped and counted twice. The help text says "the number of single-replica ledgers skipped".

Reproduced with one single-replica ledger indexed under two failed bookies: testAdvSingleLedgerOnTwoFailedBookiesCountsAsOneSkippedLedger fails with one ledger was skipped expected:<1> but was:<2>. The same ledger on one bookie counts 1 (control passes). Since the doc tells operators to alert on this counter, the value grows with the number of failed bookies. Suggest grouping ledgers across the lost bookies before publishing (one publish per ledger with all its missing bookies), or de-duplicating the skip count per audit run.

.log("Skipping underreplicated mark");
return FutureUtils.Void();
} else {
underReplicatedSize.add(metadata.getValue().getLength());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Test gap: nothing asserts getUnderReplicatedLedgerTotalSize(). I removed just this underReplicatedSize.add(...) line and every test in AuditorBookieCheckTaskTest still passed.

A test that fails without the line and passes with it (one ledger with writeQuorumSize=2 and getLength() returning 4096, with the size stat mocked):

bookieCheckTask.publishSuspectedLedgersAsync(Lists.newArrayList("127.0.0.1:1000"), ledgerIds).join();
verify(sizeStats).registerSuccessfulValue(4096L);

The description says size is counted "only for ledgers actually submitted", so a case with a skipped single-replica ledger next to a published one would pin that as well.

Set<LedgerFragment> fragments = getUnderreplicatedFragments(lh,
conf.getAuditorLedgerVerificationPercentage());
try {
if (skipHistoricalSingleReplicaLedger(ledgerIdToReplicate)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cost note (not measured): this guard runs for every ledger the worker handles, not just single-replica ones. For a normal ledger it reads the underreplication znode (getLedgerUnreplicationInfo) and, when the replica list is non-empty, does a blocking readLedgerMetadata; then admin.openLedgerNoRecovery below reads the same metadata again. After a bookie failure with a large number of ledgers that is extra ZooKeeper work on the recovery hot path.

Possible alternative: open the ledger first and check lh.getLedgerMetadata().getWriteQuorumSize() == 1 on the handle you already have, keeping the replica-list check on the underreplication info you already read. (I did not run TestReplicationWorker, which needs real bookies, so this comes from reading the code.)

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.

Prevent endless AutoRecovery retries for single-replica ledgers

3 participants