Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGES/+advisory-child-detection-queries.bugfix
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Resolve the packages and modules referenced by copied advisories with one query each instead of one per advisory.
111 changes: 67 additions & 44 deletions pulp_rpm/app/tasks/copy.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from django.db import transaction
from django.db.models import BooleanField
from django.db.models.expressions import RawSQL
from contextlib import contextmanager

from django.db import connection, transaction
from django.db.models import Exists, OuterRef
from django.db.models.fields.json import KeyTextTransform

from pulpcore.plugin.models import Content, RepositoryVersion
from pulpcore.plugin.util import get_domain_pk
Expand All @@ -13,11 +15,34 @@
PackageEnvironment,
PackageGroup,
RpmRepository,
UpdateCollection,
UpdateCollectionPackage,
UpdateRecord,
)
from pulp_rpm.app.sql_utils import annotate_with_age, get_content_in_repoversion, safe_in


@contextmanager
def _hash_join_only():
"""Force hash or merge joins for the child-detection queries.

PostgreSQL estimates the advisory subquery from the repository-version content array at a
handful of rows, so a nested-loop plan looks cheap even when the collection rows number in
the millions; that plan degrades to a quadratic scan. With nested loops disabled the planner
must use a hash or merge join, both linear in their inputs and spilled to disk once they
exceed ``work_mem``.
"""
with connection.cursor() as cursor:
cursor.execute("SHOW enable_nestloop")
previous = cursor.fetchone()[0]
cursor.execute("SELECT set_config('enable_nestloop', 'off', false)")
try:
yield
finally:
with connection.cursor() as cursor:
cursor.execute("SELECT set_config('enable_nestloop', %s, false)", [previous])


def find_children_of_content(content, src_repo_version):
"""Finds the content referenced directly by other content and returns it all together.

Expand Down Expand Up @@ -58,47 +83,45 @@ def find_children_of_content(content, src_repo_version):

# --- Advisories: resolve the packages and modules they reference ---
domain_pk = get_domain_pk()
for advisory in advisories.iterator():
package_nevras = advisory.get_pkglist()
if package_nevras:
# Uses a single unnest()-zipped array comparison (avoid param blow)
names, epochs, versions, releases, arches = zip(*package_nevras)
matching_packages = (
packages.filter(pulp_domain=domain_pk)
.annotate(
_nevra_match=RawSQL(
'("rpm_package"."name", "rpm_package"."epoch", "rpm_package"."version", '
'"rpm_package"."release", "rpm_package"."arch") IN '
"(SELECT * FROM unnest(%s::text[], %s::text[], %s::text[], "
"%s::text[], %s::text[]))",
(list(names), list(epochs), list(versions), list(releases), list(arches)),
output_field=BooleanField(),
)
)
.filter(_nevra_match=True)
)
children.update(matching_packages.values_list("pk", flat=True))

module_nsvcas = advisory.get_module_list()
if module_nsvcas:
# Uses a single unnest()-zipped array comparison (avoid param blow)
names, streams, versions, contexts, arches = zip(*module_nsvcas)
matching_modules = (
modules.filter(pulp_domain=domain_pk)
.annotate(
_nsvca_match=RawSQL(
'("rpm_modulemd"."name", "rpm_modulemd"."stream", '
'"rpm_modulemd"."version", "rpm_modulemd"."context", '
'"rpm_modulemd"."arch") IN '
"(SELECT * FROM unnest(%s::text[], %s::text[], %s::text[], "
"%s::text[], %s::text[]))",
(list(names), list(streams), list(versions), list(contexts), list(arches)),
output_field=BooleanField(),
)
)
.filter(_nsvca_match=True)
)
children.update(matching_modules.values_list("pk", flat=True))
advisory_packages = UpdateCollectionPackage.objects.filter(
update_collection__update_record__in=advisories,
name=OuterRef("name"),
epoch=OuterRef("epoch"),
version=OuterRef("version"),
release=OuterRef("release"),
arch=OuterRef("arch"),
)
advisory_modules = (
UpdateCollection.objects.filter(
update_record__in=advisories,
module__isnull=False,
)
.annotate(
module_name=KeyTextTransform("name", "module"),
module_stream=KeyTextTransform("stream", "module"),
module_version=KeyTextTransform("version", "module"),
module_context=KeyTextTransform("context", "module"),
module_arch=KeyTextTransform("arch", "module"),
)
.filter(
module_name=OuterRef("name"),
module_stream=OuterRef("stream"),
module_version=OuterRef("version"),
module_context=OuterRef("context"),
module_arch=OuterRef("arch"),
)
)
with _hash_join_only():
children.update(
packages.filter(pulp_domain=domain_pk)
.filter(Exists(advisory_packages))
.values_list("pk", flat=True)
)
children.update(
modules.filter(pulp_domain=domain_pk)
.filter(Exists(advisory_modules))
.values_list("pk", flat=True)
)

# --- PackageCategories & PackageEnvironments: resolve the PackageGroups they reference ---
# (must go before the PackageGroups section below, which needs the full group set)
Expand Down
8 changes: 1 addition & 7 deletions pulp_rpm/tests/unit/performance/test_copy.py
Original file line number Diff line number Diff line change
Expand Up @@ -218,18 +218,12 @@ def test_query_count_is_size_invariant(self, profile_name, save_artifact):
SMALL_COUNT = 20
SCALE_FACTOR = 10
LARGE_COUNT = SMALL_COUNT * SCALE_FACTOR
IGNORE_PATHS = [
IgnoreFromPath(
pattern=r"advisory\.py:\d+ in (get_pkglist|get_module_list)",
reason="needs further investigation",
),
]

small = self.call_copy_workflow(SMALL_COUNT, profile_name)
large = self.call_copy_workflow(LARGE_COUNT, profile_name)
save_artifact(small.recorder.summary_text(include_sql=True), suffix="small")

not_ignored = make_not_ignored_filter(IGNORE_PATHS)
not_ignored = make_not_ignored_filter()
small_queries = small.recorder.get_queries(not_ignored)
large_queries = large.recorder.get_queries(not_ignored)
offenders = detect_n1(small_queries, large_queries)
Expand Down
52 changes: 52 additions & 0 deletions pulp_rpm/tests/unit/test_copy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Unit tests for child detection in the copy task."""

import uuid

import pytest
from django.db import connection

from pulp_rpm.app.models import RpmRepository
from pulp_rpm.app.tasks.copy import _hash_join_only, copy_content
from pulp_rpm.tests.unit.utils.content_factory import RepoContentFactory


@pytest.mark.django_db
def test_children_of_every_selected_advisory_are_copied():
"""Each advisory in the selection contributes its referenced packages."""
with RepoContentFactory(repo_name="multi-advisory") as repo:
package_pks = repo.add_packages(["first-package", "second-package"])
first_advisory = repo.add_advisory("ADV-1", package_names=["first-package"])
second_advisory = repo.add_advisory("ADV-2", package_names=["second-package"])
source_version = repo.version

dest_repo = RpmRepository.objects.create(name=str(uuid.uuid4()))
copy_content(
[
{
"source_repo_version": source_version.pk,
"dest_repo": dest_repo.pk,
"content": [first_advisory, second_advisory],
}
],
dependency_solving=False,
)

copied = set(dest_repo.latest_version().content.values_list("pk", flat=True))
assert set(package_pks) | {first_advisory, second_advisory} <= copied


@pytest.mark.django_db
def test_hash_join_only_is_scoped_to_the_block():
"""Child detection disables nested loops only while its queries run."""
with connection.cursor() as cursor:
cursor.execute("SHOW enable_nestloop")
before = cursor.fetchone()[0]

with _hash_join_only():
with connection.cursor() as cursor:
cursor.execute("SHOW enable_nestloop")
assert cursor.fetchone()[0] == "off"

with connection.cursor() as cursor:
cursor.execute("SHOW enable_nestloop")
assert cursor.fetchone()[0] == before
Loading