Skip to content

osd/PeeringState: track the PG vulnerability window via last_degraded/last_clean, repurpose PG rebuild duration counter - #72144

Merged
sseshasa merged 9 commits into
ceph:mainfrom
sseshasa:wip-fix-pg-vulnerability-full-solution
Oct 14, 2026
Merged

sseshasa merged 9 commits into
ceph:mainfrom
sseshasa:wip-fix-pg-vulnerability-full-solution

Conversation

@sseshasa

@sseshasa sseshasa commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Replace the interim in-memory rebuild-stats latch (rebuild_start_time/rebuild_base_recovered/rebuild_had_redundancy_loss and try_record_rebuild_segment(), plus the handover-away recording) with a direct read of the peered pg_stat_t timestamps, and restore the longest/shortest single-window statistics.

The main latch mechanics in prepare_stats_for_publish(), on the primary performs the following:

  • snapshots vulnerability_window_was_open = (last_degraded > last_clean)
    before the clean-stamp advances last_clean;
  • on a vulnerable publish with no window open, latches last_degraded to
    last_change (the onset), extending the existing last_degraded latch to
    also arm on num_degraded>0 / num_misplaced>0, not just the
    DEGRADED/UNDERSIZED state bits;
  • on the publish where the window closes (not vulnerable, and last_clean
    has advanced past last_degraded), adds (last_clean - last_degraded) to
    the renamed rs_pg_vulnerability_duration counter exactly once via
    tinc_with_max(). The LONGRUNAVG's max_inc field tracks the longest
    single window, and updates a companion add_time() gauge
    pg_vulnerability_duration_min via
    PerfCounters::set_min_nonzero(dur.to_nsec()) for the shortest; then
    collapses last_degraded up to last_clean so the closed window is never
    re-recorded (by a later publish, a peer, or this OSD after a restart).

Other important changes:

  1. Adds last_degraded/last_clean/vuln_window_reported to pg_history_t (peered and persisted).
  2. This also restores the min/max single-window stats the interim solution dropped. The min is recorded at nanosecond resolution, so a sub-second window is no longer truncated to 0.

The above changes result in the following:

  • A PG that stays continuously vulnerable under one primary across any
    number of peering-interval restarts is recorded as a single sample
    without per-segment fragmentation.
  • Empty / dataless vulnerability windows are now counted (the interim
    delta_recovered / had_redundancy_loss filter is dropped): the counter
    now measures total exposure time - the whole open-to-clean window,
    whether or not any data ever moved.
  • PG split needs no rebuild-stats-specific handling: split_into() already
    copies the whole pg_stat_t (last_degraded/last_clean) to the child, and
    finish_split_stats()'s num_objects_recovered re-anchoring is no longer
    relevant. The delta_recovered-goes-negative-on-split bug class is gone
    with the field.
  • The new Counter rs_pg_vulnerability_duration with the exposed
    pg_vulnerability_duration schema string (unchanged) tracks the total
    exposure time - the whole open-to-clean window whether or not any
    data ever moved. A new rs_pg_vulnerability_duration_min gauge is added.
  • The pre-existing counter rs_pg_rebuild_duration is repurposed to measure the
    active-recovery-only span/window - with companion min/max gauges.

Tests:

  • Adds tests for PerfCounters::set_min_zero() in src/test/perf_counters.cc
  • Adds tests to test the encoding bump topg_history_t(adds last_degraded/last_clean/vuln_window_reported fields) - see src/test/osd/types.cc
  • Updates/Adds multiple tests in src/test/osd/TestPeeringState.cc to verify the latch mechanics under various conditions
  • Updates/Adds multiple tests in qa/standalone/osd/[osd-recovery-stats.sh/divergent-priors.sh] to simulate various conditions to verify that both pg_vulnerability_counter and pg_rebuild_counter are set correctly.

Fixes: https://tracker.ceph.com/issues/80967
Assisted-by: Claude Sonnet 5
Signed-off-by: Sridhar Seshasayee [email protected]

Contribution Guidelines

  • To sign and title your commits, please refer to Submitting Patches to Ceph.

  • If you are submitting a fix for a stable branch (e.g. "quincy"), please refer to Submitting Patches to Ceph - Backports for the proper workflow.

  • When filling out the below checklist, you may click boxes directly in the GitHub web UI. When entering or editing the entire PR message in the GitHub web UI editor, you may also select a checklist item by adding an x between the brackets: [x]. Spaces and capitalization matter when checking off items this way.

Checklist

  • Tracker (select at least one)
    • References tracker ticket
    • Very recent bug; references commit where it was introduced
    • New feature (ticket optional)
    • Doc update (no ticket needed)
    • Code cleanup (no ticket needed)
  • Component impact
    • Affects Dashboard, opened tracker ticket
    • Affects Orchestrator, opened tracker ticket
    • No impact that needs to be tracked
  • Documentation (select at least one)
    • Updates relevant documentation
    • No doc update is appropriate
  • Tests (select at least one)
Show available Jenkins commands

You must only issue one Jenkins command per-comment. Jenkins does not understand
comments with more than one command.

Atomically lower a gauge to a new value if it is smaller than the current
one, treating a current 0 as "unset" so the first sample always lands (a 0
argument is ignored). Implemented as a single compare-exchange loop, in the
same style as inc_with_max()'s max_u64_inc tracking.

This is the running-min counterpart that inc_with_max() / tinc_with_max()
already provide for the max. Tracking a min with a caller-side
get()+compare+set() sequence is not atomic as a whole even though the
individual calls are, so two callers updating one shared counter (e.g.
several PG shards on a single OSD-wide PerfCounters object) can race and
lose the lower value. Accepts a plain u64 gauge or a non-avg time gauge
(value in nanoseconds, see tset()).

Adds SetMinNonzero (basic / 0-ignored), SetMinNonzeroConcurrent (8
threads race a shared gauge; the true minimum must survive) and
SetMinNonzeroTimeGauge (nanosecond time gauge: a sub-second value is not
truncated, round-trips via get()/tget()) to src/test/perf_counters.cc.

Fixes: https://tracker.ceph.com/issues/80967
Signed-off-by: Sridhar Seshasayee <[email protected]>
@sseshasa

Copy link
Copy Markdown
Contributor Author

jenkins test make check

@sseshasa

Copy link
Copy Markdown
Contributor Author

jenkins test make check arm64

@sseshasa

Copy link
Copy Markdown
Contributor Author

jenkins test api

@rzarzynski
rzarzynski self-requested a review September 28, 2026 14:58
@sseshasa
sseshasa force-pushed the wip-fix-pg-vulnerability-full-solution branch from 5c8c3e5 to a3c7d9b Compare September 28, 2026 15:14
@batrick

batrick commented Sep 29, 2026

Copy link
Copy Markdown
Member

@rzarzynski need ack that this is a 21.1.2 blocker.

@sseshasa
sseshasa requested a review from ronen-fr September 30, 2026 15:12
@sseshasa

Copy link
Copy Markdown
Contributor Author

@ronen-fr If you have the bandwidth, could you please review the code changes for this full solution? You had reviewed the interim solution changes not too long ago and so you would have some context for this PR. Thanks!

@ronen-fr

ronen-fr commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

First - what Claude has to say:
Minor issues:

  • Outdated help text: the counter description still says the times come from pg_stat_t; they now come from pg_history_t.
  • Doc claim: the doc says both counters survive primary handovers. pg_rebuild_duration doesn't; it is dropped when this OSD stops being primary.
  • Merge-source publish (commit 9f73b94): it probably never does anything, because a PG must already be clean before it can be merged away. It's harmless.
  • The window start isn't saved to disk right away. The PR doesn't mark the PG info as needing a write when it records the start, so it's only saved when something else writes it. I only fixed this for the window closing. The commit message's claim that the window "survives OSD restarts" mostly depends on the start being saved during activation or later recovery writes.

The forth one is the most interesting in my view.

Also, a more important possible race:

"Replica history bug (the main one). It isn't a race in the timing sense; it's an ordering mistake. try_mark_clean() sent the PG info to replicas before the publish that closes and records the window. If the primary later fails before another info share, the new primary records the same episode again, stretched across the healthy time in between. " or

"Replicas can keep a window open that the primary already closed (likely bug). In try_mark_clean() (PeeringState.cc:3772-3773), share_pg_info() runs before publish_stats_to_osd(). The window is closed and marked as recorded inside that publish, so replicas receive a history that still shows it open from T1.

If the primary dies before the PG info is shared again (a scrub or an interval change), a replica becomes primary and inherits that start time.
Its next clean then records one window from T1, including the whole healthy period in between, and counts the first episode a second time.
Fix: publish before sharing, or share again after the publish."

I have a fix for that, in gist https://gist.github.com/ronen-fr/7acc339a2ae0a3e309836159ebab8e0e, if you want to take a look at it.
The main fix there is simply switching the order of share_pg_info() and publish_stats_to_osd() in PeeringState::try_mark_clean().

@ronen-fr

ronen-fr commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

Nit of nits: 'dur' can be made const in close_rebuild_span()

Comment thread src/osd/OSD.cc Resolved
@ronen-fr

ronen-fr commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

LGTM otherwise

@ronen-fr

ronen-fr commented Oct 1, 2026

Copy link
Copy Markdown
Contributor

@sseshasa - Hi Sridhar. I think I have, by mistake, pushed a commit into your branch (when trying to push to my 'origin'). I can't remove it with 'force-w', and don't want to cause any more damage. Apologies.

@sseshasa
sseshasa force-pushed the wip-fix-pg-vulnerability-full-solution branch from a3376f0 to a3c7d9b Compare October 2, 2026 04:52
@sseshasa

sseshasa commented Oct 2, 2026

Copy link
Copy Markdown
Contributor Author

@sseshasa - Hi Sridhar. I think I have, by mistake, pushed a commit into your branch (when trying to push to my 'origin'). I can't remove it with 'force-w', and don't want to cause any more damage. Apologies.

@ronen-fr No worries. I addressed it. And thanks for your review comments! I will take a look.

@sseshasa
sseshasa force-pushed the wip-fix-pg-vulnerability-full-solution branch 2 times, most recently from c35ffc2 to f4b0ced Compare October 5, 2026 11:58
@sseshasa

sseshasa commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Nit of nits: 'dur' can be made const in close_rebuild_span()

Done. Changed to const.

@sseshasa

sseshasa commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

I will try to respond to each of your comments below:

* Outdated help text: the counter description still says the times come from pg_stat_t; they now come from pg_history_t.

Updated now to reflect the correct behavior.

* Doc claim: the doc says both counters survive primary handovers. pg_rebuild_duration doesn't; it is dropped when this OSD stops being primary.

I added changes to make both counters restart resilient. See pg_history_t changes and the associated commit that sources the latches from it.

* Merge-source publish (commit [9f73b94](https://github.com/ceph/ceph/commit/9f73b94648d18c78ee0fc9a12fda6049149fd667)): it probably never does anything, because a PG must already be clean before it can be merged away. It's harmless.

Yes, this commit was removed.

* The window start isn't saved to disk right away. The PR doesn't mark the PG info as needing a write when it records the start, so it's only saved when something else writes it. I only fixed this for the window closing. The commit message's claim that the window "survives OSD restarts" mostly depends on the start being saved during activation or later recovery writes.

Thanks for catching this. The commits e1ec246, 80768bc and dd466ce use the dirty_info and ensure window starts are saved to disk on onset too, not only on close.

Also, a more important possible race:

"Replica history bug (the main one). It isn't a race in the timing sense; it's an ordering mistake. try_mark_clean() sent the PG info to replicas before the publish that closes and records the window. If the primary later fails before another info share, the new primary records the same episode again, stretched across the healthy time in between. " or
...
I have a fix for that, in gist https://gist.github.com/ronen-fr/7acc339a2ae0a3e309836159ebab8e0e, if you want to take a look at it. The main fix there is simply switching the order of share_pg_info() and publish_stats_to_osd() in PeeringState::try_mark_clean().

Yes, this is legitimate bug. The commit 1156f34 leverages the changes suggested in your gist and develops the solution to handle this gap for both the counters. Note that the variable name used is generic - rebuild_stats_close_unshared. Please note that I have included Co-authored by you for this fix since you pretty much provided the solution for it.

@sseshasa

sseshasa commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

LGTM otherwise

@ronen-fr I think most of your comments are addressed. Please take a look. Thanks!

@sseshasa
sseshasa force-pushed the wip-fix-pg-vulnerability-full-solution branch 2 times, most recently from a7e4b6c to c2c32e1 Compare October 6, 2026 17:29
@sseshasa

sseshasa commented Oct 7, 2026

Copy link
Copy Markdown
Contributor Author

LGTM otherwise

@ronen-fr I think most of your comments are addressed. Please take a look. Thanks!

@ronen-fr When possible, please take a look if your comments are addressed. Thanks!

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

Generally LGTM with some nits, questions and – importantly – the request to emphasize that benign rebalances affect the counters.

Comment on lines +299 to +307
// There is no built-in running *min*, and a caller-side get()+compare+set()
// min is not atomic as a whole - two callers can race and lose an update.
// This is the missing min: a single compare-exchange loop, in the same style
// as inc_with_max()'s. A current value of 0 counts as "unset" so the first
// sample always lands, after which it only moves downward.
uint64_t cur;
do {
cur = data.u64.load();
} while ((cur == 0 || amt < cur) && !data.u64.compare_exchange_weak(cur, amt));

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.

OK.

Comment thread src/osd/PeeringState.cc Outdated
Comment on lines +4433 to +4440
// Snapshot whether a vulnerability window is currently open, *before* the
// clean-stamp below advances last_clean. last_degraded > last_clean means
// a window opened and has not yet been closed/recorded; once last_clean is
// re-stamped to "now" for a clean PG, that ordering no longer tells us
// whether the window closed on this very publish or many publishes ago.
// See the vulnerability-window block further down.
const bool vulnerability_window_was_open =
info.stats.last_degraded > info.stats.last_clean;

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.

Agreed.

Comment thread src/osd/PeeringState.cc Outdated
Comment on lines +4554 to +4561
* Scope: this counter measures *exposure* time, not data-movement time.
* An empty or dataless window still counts (durability risk exists from
* the state transition itself, independent of whether any object was
* ever at risk), and a misplacement-only window (e.g. benign CRUSH
* rebalancing) still counts, indistinguishable here from a genuine failure
* -- separating those needs OSDMap correlation, NOT scoped in the current
* solution. A companion counter for the active recovery/backfill portion
* of the window only is added in a follow-up change.

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.

ACK.

Comment thread src/osd/PeeringState.h Outdated
Comment on lines +2376 to +2392
/**
* Vulnerability-window tracking (last_degraded/last_clean in info.stats)
* is gated by is_primary(): only the primary ever advances it, so a replica
* has no way to correctly finish (record) a window it did not open
* itself. Call this right after any code path that adopts a peer's
* pg_stat_t wholesale -- if the inherited info.stats carried an
* open-but-unrecorded window (last_degraded > last_clean), collapse it so
* this OSD's local copy always reads "no window open". Without this, a
* replica silently inherits a stuck, already resolved onset from whichever
* primary sent the info, and permanently fails to track its own vulnerability
* the next time it becomes primary.
*/
void discard_inherited_vulnerability_window() {
if (info.stats.last_degraded > info.stats.last_clean) {
info.stats.last_degraded = info.stats.last_clean;
}
}

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.

Agreed.

Comment thread src/osd/PeeringState.cc Outdated
ps->state_set(PG_STATE_BACKFILLING);
pl->on_backfill_reserved();
// Arm the active-rebuild latch unless a span is already in progress.
if (ps->rebuild_active_start == utime_t()) {

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.

It would be easier to scan for all places we start the counting if there is a dedicated method like arm_rebuild_span().

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Makes sense. I will add it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added in the latest push.

Comment thread src/osd/PeeringState.cc Outdated
// Arm the active-rebuild latch (rs_pg_rebuild_duration) unless a
// span is already in progress
if (ps->rebuild_active_start == utime_t()) {
ps->rebuild_active_start = ceph_clock_now();

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.

Ouch, initially I missed the arming place for the PGLog-based recovery and had to reread the commit. Having a dedicated method would make grepping easier.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed. Will add it.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Added now.

Comment thread src/osd/osd_types.cc
void pg_history_t::encode(ceph::buffer::list &bl) const
{
ENCODE_START(10, 4, bl);
ENCODE_START(11, 4, bl);

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.

ACK for the encode part.

Comment thread src/osd/osd_types.cc
void pg_history_t::decode(ceph::buffer::list::const_iterator &bl)
{
DECODE_START_LEGACY_COMPAT_LEN(10, 4, 4, bl);
DECODE_START_LEGACY_COMPAT_LEN(11, 4, 4, bl);

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.

ACK for the decode part.

Comment thread src/osd/osd_types.h
* marker (tied to last_clean's own advance) that gates re-recording, so
* last_degraded itself never needs to be artificially moved.
*/
utime_t last_degraded;

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.

We're growing the pg_history_t by 6 * 8 bytes members. Rather should be fine but I would like to ensure there is no impact on peering.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I too think the 48 bytes addition shouldn't be a problem. This is considering the sizes of the other structures in pg_info_t for e.g., pg_stats_t whose object_stat_sum_t alone is >100 bytes among other fields. In addition, this change doesn't affect the per-object hot path or client I/O path. Although code is currently only tested at smallest scale without any issue observed, CI + the eventual downstream tests would act as a good indicator of the effect. I can ask QE to keep a watch on the before/after peering-latency during their tests.

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.

I can ask QE to keep a watch on the before/after peering-latency during their tests.

Sounds reasonable!

- The counters are **per OSD, not per PG** -- they answer "how much did
this OSD's PGs collectively spend degraded," not "how many times has
this specific PG been rebuilt."
- A benign CRUSH rebalance (reweight, added capacity, a ``pg_num``

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.

I think it would be important to emphasize this. I wonder all automata (scaler, balancers) can severely affect these new metrics.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed. I have expanded on this point in the docs and how to check balancer/autoscaler activity around suspicious spikes. The point also adds its planned yet-to-be implemented mitigation. Please take a look.

@ronen-fr

ronen-fr commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

My comments were addressed. Thanks.
LGTM.
Radek had some good suggestions regarding the organization of the code.

@sseshasa
sseshasa force-pushed the wip-fix-pg-vulnerability-full-solution branch 2 times, most recently from 4263219 to 9ba3585 Compare October 7, 2026 19:56
@sseshasa
sseshasa force-pushed the wip-fix-pg-vulnerability-full-solution branch from 9ba3585 to 4cb3d73 Compare October 8, 2026 05:52
@sseshasa

sseshasa commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

Generally LGTM with some nits, questions and – importantly – the request to emphasize that benign rebalances affect the counters.

@rzarzynski I addressed your comments. Please take a look.

Comment on lines +602 to +623
- A benign, automated rebalance -- the **balancer** or
**pg_autoscaler** moving already-redundant data, a manual reweight,
or added capacity -- is currently counted the same as a genuine
failure; cause attribution is not yet implemented. Both are enabled
by default (the balancer in ``upmap`` mode, autoscaling ``on`` for
new pools) and each evaluates for a possible change roughly every 60
seconds -- this is continuous background activity, not an occasional
event, so on an actively-managed cluster the *cumulative* totals of
these counters can end up dominated by benign rebalancing rather
than genuine incidents. ``ceph pg dump``'s ``num_objects_degraded``/
``num_objects_misplaced`` split does **not** reliably distinguish
the two cases -- backfill's own accounting can attribute a purely
cosmetic rebalance to ``num_objects_degraded`` whenever a backfill
target's deficit can't be paired against a matching source-side
entry, with no actual data at risk. To check whether one was active
around a suspicious spike: ``ceph balancer status`` reports
``last_optimize_started``/``last_optimize_duration`` directly, and
``ceph -s`` (or ``ceph progress``) shows a live "PG autoscaler
increasing/decreasing pool ... PGs" entry while pg_autoscaler is
actively resizing a pool. A proper fix (classifying cause directly
from OSDMap/interval history) is tracked as a separate,
not-yet-implemented effort.

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.

Thank you! Now it's very explicitly said.
BTW: I wouldn't be surprised of there is an overlap between people who disable the automata and those who might be interested in the new metrics.

@sseshasa

sseshasa commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

jenkins test windows

…/last_clean

Replace the interim in-memory rebuild-stats latch
(rebuild_start_time/rebuild_base_recovered/rebuild_had_redundancy_loss and
try_record_rebuild_segment(), plus the handover-away recording) with
a direct read of the peered pg_stat_t timestamps, and restore the
longest/shortest single-window statistics.

prepare_stats_for_publish() now, on the primary:

 - snapshots vulnerability_window_was_open = (last_degraded > last_clean)
   before the clean-stamp advances last_clean;
 - on a vulnerable publish with no window open, latches last_degraded to
   last_change (the onset), extending the existing last_degraded latch to
   also arm on num_degraded>0 / num_misplaced>0, not just the
   DEGRADED/UNDERSIZED state bits;
 - on the publish where the window closes (not vulnerable, and last_clean
   has advanced past last_degraded), adds (last_clean - last_degraded) to
   the renamed rs_pg_vulnerability_duration counter exactly once via
   tinc_with_max(). The LONGRUNAVG's max_inc field tracks the longest
   single window, and updates a companion add_time() gauge
   pg_vulnerability_duration_min via
   PerfCounters::set_min_nonzero(dur.to_nsec()) for the shortest; then
   collapses last_degraded up to last_clean so the closed window is never
   re-recorded (by a later publish, a peer, or this OSD after a restart).

This also restores the min/max single-window stats the interim solution
dropped (commit "drop pg_rebuild_max_secs/min_secs ..."). The min is recorded
at nanosecond resolution, so a sub-second window is no longer truncated to 0.

The above changes result in the following:

- A PG that stays continuously vulnerable under one primary across any
  number of peering-interval restarts is recorded as a single sample
  without per-segment fragmentation.
- Empty / dataless vulnerability windows are now counted (the interim
  delta_recovered / had_redundancy_loss filter is dropped): the counter
  now measures total exposure time - the whole open-to-clean window,
  whether or not any data ever moved.
- PG split needs no rebuild-stats-specific handling: split_into() already
  copies the whole pg_stat_t (last_degraded/last_clean) to the child, and
  finish_split_stats()'s num_objects_recovered re-anchoring is no longer
  relevant. The delta_recovered-goes-negative-on-split bug class is gone
  with the field.
- Counter rs_pg_rebuild_duration is renamed to rs_pg_vulnerability_duration;
  the exposed "pg_vulnerability_duration" schema string is unchanged. A new
  rs_pg_vulnerability_duration_min gauge is added.

In addition to the above, there were places in the code that resulted in a
replica applying the primary's pg_state_t onto it's own info.stats. This results
in the replica getting permanently stuck the next time it becomes primary:
silently (no re-open, no record) if it never reaches clean while primary, or
with a wildly inflated duration if it does. This is fixed using
PeeringState::discard_inherited_vulnerability_window() which collapses
last_degraded to last_clean if the just-adopted info.stats shows an open
window. Called at five PeeringState/PrimaryLogPG sites.

The following are not done here, deferred to the next commit:
Persistence phase (which moves the onset into pg_history_t, the structure that
is merged across peers)

 - pg_stat_t is not synced to non-primary peers. Two unit tests
   (VulnerabilityWindowHandover, ...MultiHopHandover) and the
   reworked TEST_rebuild_perf_multihop_handover standalone test pin this
   current behavior and are the ones that change when the onset moves to
   pg_history_t.
 - A primary crash in the narrow gap between reaching clean and the next
   publish can lose or double-count that one window; a persisted
   "recorded up to" marker in pg_history_t closes this.

Tests:

 - TestPeeringState.cc: the seven RebuildStats* tests are replaced with
   seven VulnerabilityWindow* tests for the new model. Added a new test
   to verify discard_inherited_vulnerability_window().
 - qa/standalone/osd/osd-recovery-stats.sh/divergent-priors.sh: rebuild-stats
   log strings updated ("vulnerability window opened/recorded/discarded").
   The existing/new tests are updated to reflect the new model (use
   last_degraded, last_clean, check pg_vulnerability_duration.max_inc and
   pg_vulnerability_duration_min.

Fixes: https://tracker.ceph.com/issues/80967
Assisted-by: Claude Sonnet 5
Signed-off-by: Sridhar Seshasayee <[email protected]>
…pan/window

Introduces recoverystate_perf.pg_rebuild_duration (LONGRUNAVG + a
companion min gauge, OSD-wide, primary-only): the subset of a PG's
last_degraded/last_clean vulnerability window (see the parent commit)
where the PG is actually in Recovering or Backfilling, as opposed to
pg_vulnerability_duration, which spans the whole redundancy-loss
episode including any silent/paused/waiting time.

Arm/pause/close design -- one episode is recorded as a single sample,
however many times the rebuild is paused and resumed along the way:
* Armed in Recovering::Recovering()/Backfilling::Backfilling(), unless
  a span is already in progress (e.g. recovery -> backfill).
* Paused in NotRecovering::NotRecovering()/NotBackfilling::
  NotBackfilling() (defer, toofull, unfound): the new
  PeeringState::pause_rebuild_span() folds the elapsed active time into
  rebuild_active_accum and disarms the latch WITHOUT recording, so the
  paused time itself is not counted and the pause doesn't end the
  episode. A later retry re-arms a fresh span the same way as the
  first.
* Closed in Recovered::Recovered(), via close_rebuild_span(): folds any
  still-armed span into rebuild_active_accum (via pause_rebuild_span())
  one last time, then records the whole accumulated total as one
  sample and resets it. This is the dominant, everyday close point,
  since AllReplicasRecovered/Backfilled both transition straight to
  Recovered without going through either Not* state.
* Reset without recording - both rebuild_active_start and
  rebuild_active_accum - in Start::Start()'s not-primary branch, not
  in Primary::exit() (which fires on every interval restart regardless
  of role continuity and would fragment ordinary same-primary
  restarts).
* One notable asymmetry: plain RemoteReservationRevoked (backfill only)
  instead resumes through WaitLocalBackfillReserved without pausing,
  extending the same still-armed span -- inherited from how the two
  message types map to events, not a choice made here.

Deliberately not persisted across an OSD restart, unlike
pg_vulnerability_duration's onset. This is done in the next commit as part of
the persistence work.

Added perf counters (osd_perf_counters.{h,cc}): rs_pg_rebuild_duration
(add_time_avg) + rs_pg_rebuild_duration_min (add_time), exposed as
"pg_rebuild_duration" / "pg_rebuild_duration_min"

Modified existing tests to verify that the new pg_rebuild_duration perf counter
is also properly set. Added the following new tests along with some helper
functions in osd-recovery-stats.sh:
 - TEST_rebuild_perf_recovering_case
 - TEST_rebuild_perf_backfilling_case
 - TEST_rebuild_perf_backfill_toofull_pause_case
 - TEST_rebuild_perf_backfill_toofull_revoke_case
 - TEST_rebuild_perf_recovery_unfound_case
 - TEST_rebuild_perf_backfill_remote_revoke_resumes_case

All of the above also assert on pg_vulnerability_duration, directly
demonstrating the intended divergence between the two counters under
a defer/toofull/unfound/remote-revoke pause. The toofull-revoke and
unfound cases specifically assert the single-sample-per-episode
property across a real pause: pg_rebuild_duration.avgcount must stay
at its pre-episode baseline immediately after the pause (nothing
recorded yet) and land at exactly baseline+1 once the episode finally
completes (the pre-pause and post-resume spans accumulated into one
sample, not two).

Fixes: https://tracker.ceph.com/issues/80967
Assisted-by: Claude Sonnet 5
Signed-off-by: Sridhar Seshasayee <[email protected]>
…ory_t

Adds last_degraded/last_clean/vuln_window_reported AND
last_rebuild_active_start/rebuild_span_reported/rebuild_active_accum
to pg_history_t, bumps its encoding to v11 with rolling-upgrade decode
defaults(old-format instances decode to "no window open, nothing pending"
rather than retroactively discovering a pre-upgrade window), and
gives merge() a dedicated algorithm for these three fields: unlike
every other field in this struct, the window onset is not a
monotonic progress marker, so a plain max-merge is wrong for it (see
the field and merge() comments for the reasoning).

The two onset/reported pairs differ in one way: last_degraded's "is this
still open" check anchors against last_clean, a separately meaningful field.
A rebuild span has no such external anchor -- it can close without the PG
ever reaching clean - so last_rebuild_active_start's "is this still open"
check anchors against its own rebuild_span_reported marker instead.

rebuild_active_accum (the active-rebuild time accrued by the current
episode's already-paused spans, folded in by a later commit's
PeeringState::pause_rebuild_span()) only means anything relative to the
specific onset it was accrued against, so merge() makes it travel with
whichever side's onset is selected, rather than merging it
independently -- a plain max would wrongly pair one side's paused-time
total with the other side's, unrelated, earlier onset. When neither
side shows an open span, it resets to zero rather than carrying a stale
leftover value into a future episode.

Adds unit tests to unittest_osd_types (src/test/osd/types.cc)
covering merge()'s onset logic for both field pairs:
1. a normal handover,
2. a stale peer's already-superseded onset after the window closed
   elsewhere,
3. a genuine re-degrade racing a stale view, and the plain max-merge
   for vuln_window_reported,
4. a never-touched (blank) peer not disturbing an already-settled state.
5. Also adds a rolling-upgrade decode test that hand-encodes a pre-v11
   (struct_v=10) blob and confirms it decodes to the safe "no window
   open, nothing pending" default described above, rather than an
   arbitrary or uninitialized value.
6. For rebuild_active_accum specifically tests that it travels with
   whichever side's onset wins and resets to zero when neither side is open.

Purely additive - no existing pg_history_t field's behavior changes,
and nothing yet reads the new fields.

Fixes: https://tracker.ceph.com/issues/80967
Signed-off-by: Sridhar Seshasayee <[email protected]>
… transition

prepare_stats_for_publish() marks info dirty on a vulnerability-window
or active-rebuild latch arm/close transition, but not every caller of
publish_stats_to_osd() has a transaction in flight to carry that write.
An op/repop-completion callback, for instance, runs after its own
transaction has already committed, so there is nothing nearby to
piggyback on. Leaving it there would depend entirely on some unrelated
future transaction coming along to flush it which risks losing either
window.

PG::publish_stats_to_osd() is the one place every caller funnels
through regardless of context, and already has direct access to the
store/collection needed for a standalone write. It queues a standalone
transaction immediately via write_if_dirty(). The snapshot-before/
compare-after of 'was_dirty' is what keeps this rare: without it,
any already-dirty info for an unrelated reason would also trigger an
extra write on nearly every publish.

This lands before the two commits that actually mark the info dirty
(the vulnerability-window and active-rebuild latch rewires), rather
than after, so that neither of those commits is ever in a state where
dirty_info can be set and left unflushed before the PG's own lock/
unlock invariant (PG::lock()/unlock() assert !debug_has_dirty_state())
would otherwise be at risk of catching it.

That standalone write is itself unsafe during PG creation, though.
OSD::handle_pg_create_info() builds a brand-new PG's own collection-
creation transaction (MKCOLL, via create_pg_collection()/
init_pg_ondisk()) into a PeeringCtx's rctx.transaction, then calls
pg->handle_activate_map(rctx, ...) -- which can reach this exact
latch-arm path on the PG's very first stats publish, since a new PG is
routinely undersized/remapped before it has even peered -- and only
afterwards dispatches rctx.transaction to the store. If the standalone
write races ahead of that still-pending transaction, it reaches
BlueStore for a collection that doesn't exist yet, and
BlueStore::_txc_add_transaction() aborts in _get_collection().

The top level dispatchers for publish_stats_to_osd() are:
PG::do_peering_event() and PeeringState::advance_map()/activate_map()
and they already call write_if_dirty(rctx.transaction) right after
dispatching. The standalone write is therefore redundant for all of
them, and in the PG-creation window specifically, actively unsafe as
described above.

Add a dispatching_peering_event flag on PeeringState, set for the
duration of the handle_event() call at each of those three dispatchers,
and have the standalone-write branch defer to the dispatcher's own
catch-all whenever it's set.

Adds a standalone test (qa/standalone/osd/osd-recovery-stats.sh):
 - TEST_rebuild_perf_immediate_write_on_latch_transition exercises the
   original op/repop-completion gap this commit closes. Timing
   dependent and so it instead confirms the mechanism itself engages
   during an ordinary recovery episode, via its own log line as INFO.

Adds a unit test (src/test/osd/TestPeeringState.cc):
 - DispatchGuardCoversAdvanceAndActivateMap). It verifies the guard mechanism
   directly and deterministically: MockPeeringListener now records
   whether is_dispatching_peering_event() ever reads false during a
   publish_stats_to_osd() call, and the test confirms it never does
   across a PG's full initial peering cascade (the advance_map()/
   activate_map() dispatchers, and the GetInfo-to-Active/Activating cascade,
   that handle_pg_create_info() drives for a brand-new PG) and that the
   guard clears once each dispatcher returns. It can't exercise
   PG::publish_stats_to_osd()'s own branch -- that needs a real PG, which
   this PeeringState-only harness replaces with MockPeeringListener -- but
   it proves one important thing: that the guard is actually engaged
   throughout the exact dispatch window this fix depends on.

Fixes: https://tracker.ceph.com/issues/80967
Assisted-by: Claude Sonnet 5
Signed-off-by: Sridhar Seshasayee <[email protected]>
…ry_t

PeeringState::prepare_stats_for_publish() now latches
last_degraded/last_clean/vuln_window_reported in info.history instead
of info.stats: last_degraded stays pinned at the true onset once
latched (no longer collapsed to last_clean to prevent re-recording,
since vuln_window_reported now does that job), and
info.stats.last_degraded/last_clean are re-derived from info.history
on every publish, purely for external reporting (ceph pg query/pg
dump). Because pg_history_t is genuinely merged across peers on every
peering info exchange -- unlike pg_stat_t, which is only ever
wholesale-copied -- a primary handover mid-window now correctly
carries the true onset forward instead of starting a fresh window or
losing the episode entirely.

Removes discard_inherited_vulnerability_window() and its 5 call
sites: it existed to stop a replica from adopting a peer's
wholesale-copied pg_stat_t as its own unrecorded window, which is no
longer a hazard now that pg_stat_t is re-derived fresh on every
publish rather than trusted directly.

Updates the vulnerability-window unit tests (unittest_peeringstate)
for the new mechanics, including two tests that previously pinned the
old "each handover starts a fresh window" behavior -- they now assert
the new primary inherits the true onset and the whole episode is
recorded once -- and one whose premise inverted entirely: a new
replica inheriting an open window from a peer is now correct
behavior, not something to guard against.

Adds VulnerabilityWindowMarksInfoDirty unit test, confirming both
the arm and close transition mark info dirty.

Updates the two standalone tests exercising this same mechanism
end-to-end (qa/standalone/osd/):
* TEST_rebuild_perf_multihop_handover (osd-recovery-stats.sh)
* TEST_divergent_vulnerability_window (divergent-priors.sh)a

Fixes: https://tracker.ceph.com/issues/80967
Assisted-by: Claude Sonnet 5
Signed-off-by: Sridhar Seshasayee <[email protected]>
PeeringState's active-rebuild span (rs_pg_rebuild_duration) now latches
info.history.last_rebuild_active_start/rebuild_span_reported instead of
the PeeringState-local, in-memory, unpersisted rebuild_active_start
member added when the counter was first introduced. Because
pg_history_t is genuinely merged across peers on every peering info
exchange, a primary handover mid-rebuild now correctly carries the true
onset forward instead of losing it or starting a fresh span -- the same
mechanism and rationale as the preceding commit's equivalent switch-over
for the vulnerability-window latch.

The latching/arming the span is achieved through the new
PeeringState::arm_rebuild_span() method introduced here.

Removes the in-memory rebuild_active_start member and the explicit
reset in Start::Start()'s not-primary branch: that reset existed only
to stop a demoted-then-repromoted OSD from reusing a stale in-memory
value, which is no longer a hazard now that the onset lives in
pg_history_t and ordinary merge() semantics keep it correct across role
changes - the same reason last_degraded itself needs no such
special-case reset.

Marks info dirty on both the arm (Recovering::Recovering(),
Backfilling::Backfilling()) and the close (close_rebuild_span())
transition, for the same reason as the preceding commit's
vulnerability-window latch to ensure info.history is durably written
when dirty_info is set.

Adds ActiveRebuildLatchMarksInfoDirty (unittest_peeringstate),
confirming both the arm and close transition mark info dirty.

Adds a standalone test, TEST_rebuild_perf_active_rebuild_handover
(qa/standalone/osd/osd-recovery-stats.sh), that forces a genuine
Backfilling episode, kills the primary mid-backfill before it
finishes, and confirms the new primary inherits the exact
already-armed onset rather than starting a fresh one, and that the
whole episode is still recorded exactly once, spanning both primaries'
tenure.

Fixes: https://tracker.ceph.com/issues/80967
Assisted-by: Claude Sonnet 5
Signed-off-by: Sridhar Seshasayee <[email protected]>
… info

try_mark_clean() called share_pg_info() before pl->publish_stats_to_osd(),
but publish_stats_to_osd() is what actually closes a just-finished
vulnerability-window or active-rebuild episode. prepare_stats_for_
publish() advances vuln_window_reported/rebuild_span_reported there,
not before. share_pg_info() sends info.history to every peer in
acting_recovery_backfill wholesale, so calling it first meant peers
received the pre-close view: last_degraded/last_rebuild_active_start
still looking "open" relative to the not-yet-advanced reported marker.

If this OSD then stopped being primary before anything else re-shared
info (a scrub, an interval change), a promoted peer inherited that
stale, still-open-looking state. Its own next clean then recorded a
second, inflated duration for the SAME already-closed episode,
spanning all the way back to the original onset and double-counting
the healthy time in between.

Fix: swap the order, so publish_stats_to_osd() and the close it may
trigger always happens before the info that goes out to peers is
built. Confirmed that there's no hidden dependency in either direction.
This bug is unique to try_mark_clean(), the only path to PG_STATE_CLEAN.

try_mark_clean() isn't the only way to reach either close, though.
prepare_stats_for_publish() takes its close/record branch on any
publish_stats_to_osd() call where a latched, not-yet-recorded window
has reached clean, and plenty of those calls (an op's on-commit
callback, for one) have no share_pg_info() anywhere nearby.
close_rebuild_span() has the same shape from a different angle: it's
called unconditionally from Recovered::Recovered(), but the publish
right after it is itself conditional, and the only unconditional-share
path from there (GoClean -> Clean -> try_mark_clean()) only posts once
every replica is activated.

A new rebuild_stats_close_unshared flag covers both: set when either
counter's close/record branch fires, cleared by share_pg_info(), and
checked by Active::react(AdvMap) the same way it already checks
dirty_big_info -- so even a close recorded with no share in sight gets
shared on the next ordinary epoch advance, before any handover can
hand a peer the stale pre-close view.

Adds a standalone test,
TEST_rebuild_perf_replica_history_survives_handover_after_close
(qa/standalone/osd/osd-recovery-stats.sh). Deterministic, not timing-
dependent. See test's comments for more details.

Also adds two unit tests covering rebuild_stats_close_unshared's
retry-on-AdvMap path directly against the multi-PeeringState harness,
one per counter: VulnerabilityWindowCloseSharesWithReplicasOnAdvMap and
RebuildSpanCloseSharesWithReplicasOnAdvMap (src/test/osd/
TestPeeringState.cc).

Fixes: https://tracker.ceph.com/issues/80967
Assisted-by: Claude Sonnet 5
Co-authored by: Ronen Friedman <[email protected]>
Signed-off-by: Sridhar Seshasayee <[email protected]>
Adds a new section to monitoring-osd-pg.rst covering the
pg_vulnerability_duration and pg_rebuild_duration perf counters: what
each measures, where to find them via the admin socket, example PromQL
recipes for common durability-reporting use cases (weekly exposure,
MTTR, repair-vs-waiting, hot-spot triage, alerting), a CLI spot-check
via ceph pg query, and the known limitations (per-OSD not per-PG,
benign rebalance not yet distinguished from failure, inactive PGs not
counted). The PromQL examples are flagged as unverified starting
points, not tested reference recipes.

Both counters persist their onset in pg_history_t and survive OSD
restarts and primary handovers.

The section is logically placed right after "Monitoring PG States" and
before "Identifying Troubled PGs", so that a reader after learning about the
PG states can now find out how to measure the time spent in those states.

Adds PendingReleaseNotes entry with a pointer to the new documentation.

Fixes: https://tracker.ceph.com/issues/80967
Assisted-by: Claude Sonnet 5
Signed-off-by: Sridhar Seshasayee <[email protected]>
@sseshasa
sseshasa force-pushed the wip-fix-pg-vulnerability-full-solution branch from 9dcc5cd to fedd9a3 Compare October 11, 2026 15:30
@sseshasa

Copy link
Copy Markdown
Contributor Author

@sseshasa
sseshasa merged commit ff2f4a0 into ceph:main Oct 14, 2026
14 checks passed
@shraddhaag

Copy link
Copy Markdown
Contributor

Hey folks, a user reported a performance regression with this change for crimson. I have been able to verify it and its very apparent for 4k random writes. A fix for this in WIP. More details here: #72912.

cc: @Matan-B

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants