Skip to content

mgr: Fix autoscaling PG distribution - #67551

Merged
kamoltat merged 3 commits into
ceph:mainfrom
Ericmzhang:wip-improve-pg-autoscale
May 26, 2026
Merged

kamoltat merged 3 commits into
ceph:mainfrom
Ericmzhang:wip-improve-pg-autoscale

Conversation

@Ericmzhang

@Ericmzhang Ericmzhang commented Feb 26, 2026 •

Copy link
Copy Markdown
Contributor

Problem:

  • The autoscaler is allocating PGs through the pools in a first come first serve basis and not respecting target_size_ratio which from the user perspective should guarantee the ratio. This leads to certain pools with target_size_ratio not getting the correct amount of PGs.
  • The autoscaler is subtracting the target PG amount from the total instead of the actual quantized amount, resulting in an inaccurate count of the number of PGs available to be allocated.
  • The autoscaler is incorrectly allocating PGs when pg_autoscale_mode=off but bulk=true

Solution:

  • Add a dynamic programming optimization algorithm that is based on the knapsack problem. This optimization rounds each pool to the nearest power of two while aiming to keep the rounded value close to the target value. The cost is the absolute difference between the target PG value and the rounded PG value: cost = abs(pg_target - rounded_pg)
  • Update the total number of PGs available using the quantized amount instead of the target amount.
  • Add additional pass that subtracts PG NUM from pg_autoscale_mode=off pools before performing autoscaler PG allocation.

Fixes: https://tracker.ceph.com/issues/73418
https://tracker.ceph.com/issues/75424

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.

@markhpc
markhpc requested a review from a team March 5, 2026 16:27
@Ericmzhang
Ericmzhang force-pushed the wip-improve-pg-autoscale branch 3 times, most recently from 255566b to 7194591 Compare March 9, 2026 23:22

@kamoltat kamoltat left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi Eric,
super great job on this PR, it is a challenging one, but I'm glad you powered through it.
I left some comments on the code changes. It'll take me another day to review the tests.

  • I think this logical change definitely deserves some documentation changes. I would highlight the over all allocation decision of the autoscaler, how it will intelligently optimize which pool's final_pool_pg_target get rounded up to nearest power of 2, while also keep the total sum less than pg_target of the overall cluster and respect pools that have the same capacity ratio and other configurations to be rounded the same direction. Examples with calculations would be the easiest for the users to understand.

Let me know if you have any questions!

Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
backtrack.append(BacktrackNode(prev_pg_sum, parent[i][prev_pg_sum][0], parent[i][prev_pg_sum][1]))
backtrack.reverse()
return backtrack

def _calc_final_pg_target(
self,

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

The comment:

    """
    `profile` determines behaviour of the autoscaler.
    `first_pass` flag used to determine if this is the first
    pass where the caller tries to calculate/adjust pools that has
    used_ratio > even_ratio else this is the second pass,
    we calculate final_ratio by giving it 1 / pool_count
    of the root we are currently looking at.
    """

wasn't done correct by me, maybe you can improve or re-write it to include your find_optimal_pg_distribution as well (obviously no need to go into detail about the optimization function)

Comment thread src/pybind/mgr/pg_autoscaler/module.py Outdated
Comment on lines +785 to +799
bulk = False
flags = p['flags_names'].split(",")
if "bulk" in flags:
bulk = True

capacity_ratio = max(capacity_ratio, target_ratio)
final_ratio, pool_pg_target, final_pg_target = self._calc_final_pg_target(
p, pool_name, root_map, root_id,
capacity_ratio, bias, even_pools,
bulk_pools, func_pass, bulk)

if final_ratio is None:
continue

adjust = False

# Dynamic threshold only applies to scaling UP, otherwise use the default threshold.
if final_pg_target is not None and \
final_pg_target > p['pg_num_target']:
dynamic_threshold = self.get_dynamic_threshold(final_pg_target, threshold)
adjust = final_pg_target > p['pg_num_target'] * dynamic_threshold
else:
adjust = final_pg_target < p['pg_num_target'] / threshold

if adjust and \
final_ratio >= 0.0 and \
final_ratio <= 1.0 and \
p['pg_autoscale_mode'] == 'on':
adjust = True
else:
if final_pg_target != p['pg_num_target']:
self.log.warning("pool %s won't scale because recommended PG_NUM target"
" value varies from current PG_NUM value by"
" more than '%f' scaling threshold",
pool_name,
dynamic_threshold if final_pg_target > p['pg_num_target'] else threshold)

assert pool_pg_target is not None
ret.append({
'pool_id': pool_id,
'pool_name': p['pool_name'],
'crush_root_id': root_id,
'pg_autoscale_mode': p['pg_autoscale_mode'],
'pg_num_target': p['pg_num_target'],
'logical_used': float(actual_raw_used)/raw_used_rate,
'target_bytes': target_bytes,
'raw_used_rate': raw_used_rate,
'subtree_capacity': capacity,
'actual_raw_used': actual_raw_used,
'raw_used': pool_raw_used,
'actual_capacity_ratio': actual_capacity_ratio,
'capacity_ratio': capacity_ratio,
'target_ratio': p['options'].get('target_size_ratio', 0.0),
'effective_target_ratio': target_ratio,
'pg_num_ideal': int(pool_pg_target),
'pg_num_final': final_pg_target,
'would_adjust': adjust,
'bias': p.get('options', {}).get('pg_autoscale_bias', 1.0),
'bulk': bulk,
})
capacity_ratio = max(metrics['capacity_ratio'], metrics['target_ratio'])
pg_left = root_map[root_id].pg_left
pg_target = int(capacity_ratio * pg_left)

#g roup similar pools so they are all rounded the same direction
group_key = GroupKey(pg_target, p['size'], bias, bulk)
if group_key not in pool_group[root_id]:
pool_group[root_id][group_key] = PoolGroup(capacity_ratio, pg_target, p['size'], bias)
pool_group[root_id][group_key].add(pool_name, p)
self.log.info("adding pool {} with target {} size {} bias {} bulk {}".format(pool_name, pg_target, p['size'], bias, bulk))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Okay so I think we can potentially move this part out of _get_pool_pg_targets:

        even_pools: Dict[str, Dict[str, Any]] = {}
        bulk_pools: Dict[str, Dict[str, Any]] = {}
        pool_group: Dict[int, Dict[GroupKey, PoolGroup]] = defaultdict(dict) #key is (pg_target, replication size, bias, bulk)
        for pool_name, p in pools.items():
            pool_id = p['pool']
            if pool_id not in pool_stats:
                # race with pool deletion; skip
                continue

            # FIXME: we assume there is only one take per pool, but that
            # may not be true.
            crush_rule = crush_map.get_rule_by_id(p['crush_rule'])
            assert crush_rule is not None
            cr_name = crush_rule['rule_name']
            root_id = crush_map.get_rule_root(cr_name)
            assert root_id is not None
            if root_id in overlapped_roots:
                # skip pools
                # with overlapping roots
                self.log.warn("pool %d contains an overlapping root %d"
                              "... skipping scaling", pool_id, root_id)
                continue
            capacity = root_map[root_id].capacity
            assert capacity is not None
            if capacity == 0:
                self.log.debug("skipping empty subtree {0}".format(cr_name))
                continue

            bias = p['options'].get('pg_autoscale_bias', 1.0)
            metrics = self._calculate_pool_metrics(osdmap, root_map, root_id, pool_id, pool_stats, capacity, p)

            # determine if the pool is a bulk
            bulk = False
            flags = p['flags_names'].split(",")
            if "bulk" in flags:
                bulk = True

            capacity_ratio = max(metrics['capacity_ratio'], metrics['target_ratio'])
            pg_left = root_map[root_id].pg_left
            pg_target = int(capacity_ratio * pg_left)

            #g roup similar pools so they are all rounded the same direction
            group_key = GroupKey(pg_target, p['size'], bias, bulk)
            if group_key not in pool_group[root_id]:
                pool_group[root_id][group_key] = PoolGroup(capacity_ratio, pg_target, p['size'], bias)
            pool_group[root_id][group_key].add(pool_name, p)
            self.log.info("adding pool {} with target {} size {} bias {} bulk {}".format(pool_name, pg_target, p['size'], bias, bulk))

My reasoning is that all we are doing here is iterating through pools, getting options like bias, normalize target_size/target_bytes ratio, working out the capacity_ratio, construct pool_group. We can do all of this outside _get_pool_pg_targets. This will reduce redudancy by 3 times since we are calling _get_pool_pg_targets 3 times.

But by doing this we might have to return a bulk_group on the first iteration so that it can be used in _calc_final_pg_target (func pass == 'second')

Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
@Ericmzhang
Ericmzhang force-pushed the wip-improve-pg-autoscale branch from 7194591 to ce1e55e Compare March 16, 2026 19:05
@Ericmzhang
Ericmzhang force-pushed the wip-improve-pg-autoscale branch 3 times, most recently from 1e45fba to e04c873 Compare March 18, 2026 23:08
@markhpc
markhpc requested a review from a team March 19, 2026 15:16
@Ericmzhang
Ericmzhang force-pushed the wip-improve-pg-autoscale branch from e04c873 to 27f1fd7 Compare March 19, 2026 22:07

@kamoltat kamoltat left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for making the changes, I left some reviews, can discuss on the call later if need be.

Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Outdated
Comment on lines 960 to 962
# Second call make use of the even_pools we keep track of in the first call.
# All we need to do is iterate over those and give them 1/pool_count of the
# total pgs.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Might need to update the comment section here as it no longer reflects exactly what the function is doing

Comment thread src/pybind/mgr/pg_autoscaler/module.py Outdated
@@ -699,15 +960,39 @@ def _get_pool_status(
# Second call make use of the even_pools we keep track of in the first call.
# All we need to do is iterate over those and give them 1/pool_count of the
# total pgs.
pool_group: Dict[int, Dict[GroupKey, PoolGroup]] = defaultdict(dict) #key is (pg_target, replication size, bias, bulk)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

the comment on this line might not be entirely correct? Maybe include the entire
rootid: {GroupKey: PoolGroup} in the comment so it is consistence with pool_metrics below.

root_id -> { GroupKey(pg_target, size, bias, bulk) -> PoolGroup }

Also, as I reviewer I got a little confused since the var name for this nested dictionary is pool_group, however, there is also a PoolGroup class this the value of the inner dictionary layer.

pool_groups_by_root might be a better name?

Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Outdated

If any pool fails to scale during a pass, then all pools in that pass should fail to scale
"""
pgs_used_total = 0

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

pg_left is tracker per root, so we need to reset pgs_used_total for each root_id. Again I think we might want to change pool_group since it's a little confusing

@Ericmzhang
Ericmzhang force-pushed the wip-improve-pg-autoscale branch from 27f1fd7 to 8454779 Compare March 20, 2026 16:41

@kamoltat kamoltat left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Thanks for addressing the comments, here is a second round of reviews

Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
@kamoltat

Copy link
Copy Markdown
Member

we should also add comments about fixing: https://tracker.ceph.com/issues/75424
in the PR description and also add

Fixes: https://tracker.ceph.com/issues/75424 in the commit. Since this PR also fix Pools with pg_autoscale_mode=off incorrectly consume PG budget

@Ericmzhang
Ericmzhang force-pushed the wip-improve-pg-autoscale branch 3 times, most recently from 6d7e663 to a9f613a Compare March 24, 2026 20:23

@kamoltat kamoltat left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Hi @Ericmzhang thanks for making the change, lefts some feedbacks regarding the knapp sack part, bias part and some test coverages

Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think we should add the pool starvation test case here we are trying to fix: https://tracker.ceph.com/issues/73418

target_size_ratio getting set on 3 pools and the last pool doesn't receive the same ration as the other two pools.

Since it will make sure that this test case gets tested frequently in the future

@Ericmzhang
Ericmzhang force-pushed the wip-improve-pg-autoscale branch from a9f613a to bf904bc Compare April 3, 2026 23:43
@Ericmzhang
Ericmzhang force-pushed the wip-improve-pg-autoscale branch 2 times, most recently from bd73ba8 to e7347f3 Compare April 16, 2026 04:17
@Ericmzhang

Copy link
Copy Markdown
Contributor Author

Made changes from mypy

@Ericmzhang

Copy link
Copy Markdown
Contributor Author

Ericmzhang added a commit to Ericmzhang/ceph that referenced this pull request Apr 17, 2026

@kamoltat kamoltat left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@Ericmzhang There are 4 main areas that I wanted change:

  1. incorrect use of ret_copy
  2. fail_all fails exact budget
  3. grouping unmanaged pools based on pg_target rather `p['pg_num_target']
  4. max_pg clamp is comparing against the wrong var.

Comment thread src/pybind/mgr/pg_autoscaler/module.py Outdated

All final scaling decisions get checked against dynamic_threshold
"""
ret_copy = []

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@Ericmzhang
If you look closely, you are actually making duplicate entries with ret_copy.

Lets say there are two roots [-1: {pool.1, pool2}, -2: {pool.3, pool}]

iteration1:
ret_copy = [pool.1, pool2]
ret = [pool.1, pool2]

iteration2:
ret_copy = [pool.1, pool2, pool.3, pool.4]
ret = [pool.1, pool.2, pool.1, pool.2, ,pool.3, pool.4]

Your test never covered this case that's why it never fails

I would move ret_copy into the first loop

  for root_id in pool_groups_by_root:
            ret_copy = []
            final_ratios, pool_pg_targets, final_pool_pg_targets, pools = self._calculate_final_pool_pg_target(
            root_map, root_id, func_pass, pool_groups_by_root[root_id])
            fail_all = False

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.

Fixed


The autoscaler sets each pool's ``final_pool_pg_target`` to be rounded to the
nearest power of two while ensuring that the number of PGs to be placed on each OSD
will not cause its PG replicas to exceed ``mon_pgs_per_osd_target``. Pools with the same

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

typo: should be mon_target_pg_per_osd

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.

Fixed

Comment thread src/pybind/mgr/pg_autoscaler/module.py Outdated
root_map[root_id].pg_left -= pgs_used
adjust = False

if root_map[root_id].pg_left <= 0:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@Ericmzhang
What if we used up the exact budget? should we still not scale?

I think this should be:

root_map[root_id].pg_left < 0

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.

Fixed and added test case for this in qa/workunits/mon/pg_autoscaler.sh

Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Resolved
Comment thread src/pybind/mgr/pg_autoscaler/module.py Outdated
Comment on lines +547 to +549
if max_pg and max_pg < final_pool_pg_target:
final_pool_pg_target_per_replica = max_pg
final_pool_pg_target = max_pg * p['size']

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

@Ericmzhang
This seems incorrect I think it should be

Suggested change
if max_pg and max_pg < final_pool_pg_target:
final_pool_pg_target_per_replica = max_pg
final_pool_pg_target = max_pg * p['size']
if max_pg and max_pg < final_pool_pg_target_per_replica:
final_pool_pg_target_per_replica = max_pg
final_pool_pg_target = max_pg * p['size']

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.

Fixed

Add optimization algorithm to distribute PGs among pools
to minimize cost (absolute difference between target PG and rounded PG).
Fix autoscaler still allocating pools when autoscale is off but bulk is on

Fixes: https://tracker.ceph.com/issues/73418
       https://tracker.ceph.com/issues/75424
Signed-off-by: Eric Zhang <[email protected]>
Modify calc_final_pg_target test cases to reflect optimization algorithm
Add test cases that ensure cost is respected to ensure pools get rounded
closely to target

Fixes: https://tracker.ceph.com/issues/73418

Signed-off-by: Eric Zhang <[email protected]>
@Ericmzhang
Ericmzhang force-pushed the wip-improve-pg-autoscale branch from e7347f3 to bcc8d4d Compare April 20, 2026 19:53
@Ericmzhang

Copy link
Copy Markdown
Contributor Author

Made changes from above review.

@kamoltat kamoltat left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM! thanks for making the changes, lets see how it does in QA

@@ -258,7 +313,6 @@ only if there is more usage in the pool. This flag should be used with care,
as it may not have the results one would think.

To create a pool that will be flagged ``bulk``, run the following command:

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.

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.

Fixed

…escription

Update Placement Groups doc page with description of pg_autoscaler allocation algorithm.
Add example calculations showing how the algorithm prefers fairness over greedy utilization

Fixes: https://tracker.ceph.com/issues/73418

Signed-off-by: Eric Zhang <[email protected]>
@NitzanMordhai

Copy link
Copy Markdown
Contributor

@Ericmzhang
Ericmzhang force-pushed the wip-improve-pg-autoscale branch from addbd6b to 76e76f8 Compare May 26, 2026 17:42
@kamoltat
kamoltat merged commit b95bdca into ceph:main May 26, 2026
12 checks passed
@github-actions

Copy link
Copy Markdown

This is an automated message by src/script/redmine-upkeep.py.

I have resolved the following tracker ticket due to the merge of this PR:

No backports are pending for the ticket. If this is incorrect, please update the tracker
ticket and reset to Pending Backport state.

Update Log: https://github.com/ceph/ceph/actions/runs/26477815978

@ljflores

Copy link
Copy Markdown
Member

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.

8 participants