Skip to content

fix: copy cpu_flags to avoid mutating session-scoped fixture dict#4746

Open
RoniKishner wants to merge 1 commit intoRedHatQE:mainfrom
RoniKishner:wsl2-test-fix
Open

fix: copy cpu_flags to avoid mutating session-scoped fixture dict#4746
RoniKishner wants to merge 1 commit intoRedHatQE:mainfrom
RoniKishner:wsl2-test-fix

Conversation

@RoniKishner
Copy link
Copy Markdown
Contributor

@RoniKishner RoniKishner commented May 5, 2026

Short description:

Add copy.deepcopy when cpu_flags is used to create a VirtualMachineForTests

More details:

The current approach copies the object and makes changes to it. this causes pollution as the object is referenced in a session scope fixture, thus the next time the fixture is used it gets the changed values

What this PR does / why we need it:

When test_vm_windows_oom is run it changes cpu_flags = {cpu_cores: 16, cpu_threads:1} . after which TestWSL2 is run with the new values since the fixture is referencing the object and is scoped session, causing a failure due to instance type conflict.

Special notes for reviewer:

Additional changes were done to the virt.py file due to ruff check in pre-commit

Summary by CodeRabbit

  • Bug Fixes

    • Prevented unintended shared-state when updating virtual machine CPU configuration to avoid accidental mutations.
  • Refactor

    • Modernized Python type annotations across utilities for clearer, up-to-date typing.
    • Improved template variable validation logic for more reliable template processing.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 5, 2026

📝 Walkthrough

Walkthrough

This PR updates utilities/virt.py: it uses a deepcopy when assigning CPU flags to a VM template, simplifies a template-variable presence check, and modernizes several type annotations to Python 3.9+ builtin generics and union syntax. pyproject.toml and requirements.txt are also touched.

Changes

Virt utilities modernization and defensive-copy

Layer / File(s) Summary
Imports
utilities/virt.py
Added copy import to enable defensive copying (used for deepcopy).
Data Shape / Defensive Copy
utilities/virt.py
VirtualMachineForTests.update_vm_cpu_configuration() now assigns template_spec["domain"]["cpu"] = copy.deepcopy(self.cpu_flags) instead of a direct reference to self.cpu_flags.
Template Validation
utilities/virt.py
generate_dict_from_yaml_template() checks template variables with if var not in kwargs (membership) instead of if var not in kwargs.keys().
Type Annotation Updates
utilities/virt.py
Modernized annotations: Dict[str, str]dict[str, str], Dict[str, Any]dict[str, Any], List[Pod]list[Pod], and Optional[str] → `str
Manifests
pyproject.toml, requirements.txt
Project manifest files updated (listed in diff).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title directly addresses the main change: using deep-copy for cpu_flags to prevent mutation of a session-scoped fixture, which is the primary bug fix in this PR.
Description check ✅ Passed The description covers all required template sections with clear explanations of the problem, solution, and impact, including the specific failure scenario and mention of additional ruff-related changes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@openshift-virtualization-qe-bot-3
Copy link
Copy Markdown
Contributor

Report bugs in Issues

Welcome! 🎉

This pull request will be automatically processed with the following features:

🔄 Automatic Actions

  • Reviewer Assignment: Reviewers are automatically assigned based on the OWNERS file in the repository root
  • Size Labeling: PR size labels (XS, S, M, L, XL, XXL) are automatically applied based on changes
  • Issue Creation: A tracking issue is created for this PR and will be closed when the PR is merged or closed
  • Branch Labeling: Branch-specific labels are applied to track the target branch
  • Auto-verification: Auto-verified users have their PRs automatically marked as verified
  • Labels: Enabled categories: branch, can-be-merged, cherry-pick, has-conflicts, hold, needs-rebase, size, verified, wip

📋 Available Commands

PR Status Management

  • /wip - Mark PR as work in progress (adds WIP: prefix to title)
  • /wip cancel - Remove work in progress status
  • /hold - Block PR merging (approvers only)
  • /hold cancel - Unblock PR merging
  • /verified - Mark PR as verified
  • /verified cancel - Remove verification status
  • /reprocess - Trigger complete PR workflow reprocessing (useful if webhook failed or configuration changed)
  • /regenerate-welcome - Regenerate this welcome message

Review & Approval

  • /lgtm - Approve changes (looks good to me)
  • /approve - Approve PR (approvers only)
  • /assign-reviewers - Assign reviewers based on OWNERS file
  • /assign-reviewer @username - Assign specific reviewer
  • /check-can-merge - Check if PR meets merge requirements

Testing & Validation

  • /retest tox - Run Python test suite with tox
  • /retest build-container - Rebuild and test container image
  • /retest verify-bugs-are-open - verify-bugs-are-open
  • /retest all - Run all available tests

Container Operations

  • /build-and-push-container - Build and push container image (tagged with PR number)
    • Supports additional build arguments: /build-and-push-container --build-arg KEY=value

Cherry-pick Operations

  • /cherry-pick <branch> - Schedule cherry-pick to target branch when PR is merged
    • Multiple branches: /cherry-pick branch1 branch2 branch3

Label Management

  • /<label-name> - Add a label to the PR
  • /<label-name> cancel - Remove a label from the PR

✅ Merge Requirements

This PR will be automatically approved when the following conditions are met:

  1. Approval: /approve from at least one approver
  2. LGTM Count: Minimum 2 /lgtm from reviewers
  3. Status Checks: All required status checks must pass
  4. No Blockers: No wip, hold, has-conflicts labels and PR must be mergeable (no conflicts)
  5. Verified: PR must be marked as verified

📊 Review Process

Approvers and Reviewers

Approvers:

  • dshchedr
  • myakove
  • rnetser
  • vsibirsk

Reviewers:

  • RoniKishner
  • dshchedr
  • geetikakay
  • rnetser
  • vsibirsk
Available Labels
  • hold
  • verified
  • wip
  • lgtm
  • approve
AI Features
  • Cherry-Pick Conflict Resolution: Enabled (claude/claude-opus-4-6[1m])

💡 Tips

  • WIP Status: Use /wip when your PR is not ready for review
  • Verification: The verified label is removed on new commits unless the push is detected as a clean rebase
  • Cherry-picking: Cherry-pick labels are processed when the PR is merged
  • Container Builds: Container images are automatically tagged with the PR number
  • Permission Levels: Some commands require approver permissions
  • Auto-verified Users: Certain users have automatic verification and merge privileges

For more information, please refer to the project documentation or contact the maintainers.

@codecov
Copy link
Copy Markdown

codecov Bot commented May 5, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 98.67%. Comparing base (b4ad2e0) to head (06c02ec).
⚠️ Report is 127 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4746      +/-   ##
==========================================
+ Coverage   98.63%   98.67%   +0.03%     
==========================================
  Files          25       25              
  Lines        2420     2483      +63     
==========================================
+ Hits         2387     2450      +63     
  Misses         33       33              
Flag Coverage Δ
utilities 98.67% <ø> (+0.03%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@utilities/virt.py`:
- Line 3: Replace the module-level import "import copy" with a specific import
"from copy import deepcopy" to match project guidelines, and update all usages
of copy.deepcopy in this file (e.g., any calls within functions or methods that
reference copy.deepcopy) to use deepcopy directly; ensure no other references to
the copy module remain and run tests/lint to confirm compliance.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 3bdd23f5-24aa-49fa-b92a-63e69e796fa0

📥 Commits

Reviewing files that changed from the base of the PR and between 968a40a and 64125a1.

📒 Files selected for processing (1)
  • utilities/virt.py

Comment thread utilities/virt.py Outdated
Signed-off-by: rkishner <rkishner@redhat.com>
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
utilities/virt.py (1)

1-1: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

HIGH: Restore required PR template sections before merge

The provided PR description context is missing the required template headings, including meaningful content for ##### What this PR does / why we need it:. These sections are required for review/traceability automation and release hygiene.

As per coding guidelines: "##### What this PR does / why we need it: — MUST be present AND have meaningful content" and required sections must include Which issue(s) this PR fixes, Special notes for reviewer, and jira-ticket.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@utilities/virt.py` at line 1, The PR description is missing required template
sections; restore the required headings and meaningful content (at minimum add
"##### What this PR does / why we need it:", list "Which issue(s) this PR
fixes", "Special notes for reviewer", and "jira-ticket") in the PR description
before merging; reference the module context where you changed the top of the
file (the file that begins with "from __future__ import annotations") so
reviewers can confirm the commit/PR text is updated and include clear, concise
answers for each required field.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@utilities/virt.py`:
- Line 1: The PR description is missing required template sections; restore the
required headings and meaningful content (at minimum add "##### What this PR
does / why we need it:", list "Which issue(s) this PR fixes", "Special notes for
reviewer", and "jira-ticket") in the PR description before merging; reference
the module context where you changed the top of the file (the file that begins
with "from __future__ import annotations") so reviewers can confirm the
commit/PR text is updated and include clear, concise answers for each required
field.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 930a9414-6af6-4e3b-b6d5-90b3f2e84cd9

📥 Commits

Reviewing files that changed from the base of the PR and between 64125a1 and 06c02ec.

📒 Files selected for processing (1)
  • utilities/virt.py

@RoniKishner
Copy link
Copy Markdown
Contributor Author

/retest build-container

@RoniKishner
Copy link
Copy Markdown
Contributor Author

/verified

test_vm_windows_oom -> TestWSL2

@openshift-virtualization-qe-bot-3
Copy link
Copy Markdown
Contributor

@coderabbitai

Test execution plan request details

CRITICAL: You MUST post an inline review comment on the first changed line of the first file.
The inline comment should contain the Test Execution Plan with the smoke tests recommendation.
Do NOT submit a formal review - just post the inline comment directly.

As an expert software testing engineer, analyze all modified files in this PR and create a targeted test execution plan.
You will post an inline review comment with the test execution plan on the first changed file.
If you fail to run or post a comment, retry.

Analysis Requirements:

  1. Examine code changes in each modified file
  2. Identify affected code paths, functions, and classes
  3. Analyze pytest-specific elements: fixtures (scope, dependencies), parametrization, markers, conftest changes
  4. Trace test dependencies through imports, shared utilities, and fixture inheritance
  5. Detect new tests introduced in the PR
  6. Smoke Test Impact Analysis: Determine if any changes could affect smoke tests by checking:
    • Changes to files/functions used by tests marked with @pytest.mark.smoke
    • Changes to fixtures or utilities imported by smoke tests
    • Changes to conftest.py files that may affect smoke test execution
    • Changes to core infrastructure code (utilities/, libs/) that smoke tests depend on

Your deliverable:
Your change request comment will be based on the following requirements:

Test Execution Plan

  • Run smoke tests: True / False (Based on your smoke test impact analysis - True if any changes may affect smoke tests)
  • path/to/test_file.py - When the entire test file needs verification
  • path/to/test_file.py::TestClass::test_method - When specific test(s) needed
  • path/to/test_file.py::test_function - When specific test(s) needed
  • -m marker - When specific marker(s) can be used to cover multiple cases.

Guidelines:

  • Include only tests directly affected by the changes
  • Use a full file path only if ALL tests in that file require verification
  • Use file path + test name if only specific tests are needed
  • If a test marker can cover multiple files/tests, provide the marker
  • Balance coverage vs over-testing - Keep descriptions minimal

Hardware-Related Checks (SR-IOV, GPU, DPDK):

When PR modifies fixtures for hardware-specific resources:

  • Collection Safety: Fixtures MUST have existence checks (return None when hardware unavailable)
  • Test Plan: MUST verify both WITH and WITHOUT hardware:
    • Run affected tests on cluster WITH hardware
    • Verify collection succeeds on cluster WITHOUT hardware

CRITICAL WORKFLOW COMPLETION RULES:

When responding to this test execution plan request, you MUST follow these rules EXACTLY:

  1. YOUR ONLY DELIVERABLE: Post an inline review comment containing the test execution plan on the first changed line
  2. THEN STOP IMMEDIATELY - Do NOT generate any additional response
  3. FALLBACK ONLY: If submitting the review fails after retrying, post as a regular PR comment
  4. SILENCE = SUCCESS: After successfully submitting the review, your task is complete. No confirmation needed.

ABSOLUTE PROHIBITIONS (violating these creates empty/meaningless reviews):

  • ❌ Do NOT post acknowledgment messages like "Test execution plan posted", "Review posted successfully", "I've successfully posted"
  • ❌ Do NOT mention review IDs, URLs, or confirmation of posting in the PR thread
  • ❌ Do NOT add any follow-up comments after submitting the review
  • ❌ Do NOT reply to confirm task completion
  • ❌ Do NOT explain what you did - just do it and stop

Remember: The pull request review is visible to users. Additional comments are redundant noise.

CRITICAL: Before setting "Run smoke tests: True", you MUST use shell scripts to:
- Trace the actual fixture dependency chain from smoke tests to changed fixtures
- Verify that smoke tests actually import/use changed utilities or functions
- Confirm the dependency path exists; do NOT assume based on scope or semantics
- Be conservative: Session-scoped fixtures or infrastructure-sounding names do NOT
automatically mean smoke test impact. Only flag smoke test impact when you can
demonstrate a concrete dependency path.
WRONG: "This session-scoped storage fixture might affect smoke tests"
RIGHT: "Smoke test X uses fixture Y, which depends on the changed fixture Z"

Comment thread utilities/virt.py
import shlex
from collections import defaultdict
from contextlib import contextmanager
from copy import deepcopy
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 Execution Plan

  • Run smoke tests: False (No concrete dependency path found from any smoke test to the changed cpu_flags/n fixture handling; smoke test files test_container_disk_vm.py and test_rhel_os_support.py do not use cpu_flags or vm_n.)

Directly affected tests (must run):

  • tests/virt/node/general/test_wsl2.py::TestWSL2 — regression target; uses vm_cpu_flagsVirtualMachineForTests(cpu_flags=...) → the now-deepcopied self.cpu_flags
  • tests/virt/node/general/test_oom.py::test_vm_windows_oom — mutation source; sets cpu_cores=16, cpu_threads=1 which previously polluted the session-scoped fixture

Secondary (use n/cpu_flags param on VirtualMachineForTests):

  • tests/virt/node/node_labeller/cpu_features/test_vm_with_cpu_flag.py
  • tests/virt/node/node_labeller/cpu_features/test_vm_with_cpu_features.py

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 5, 2026

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Find WSL2 test file
fd -i "wsl2" --type f

# Find test_vm_windows_oom
rg -rn "test_vm_windows_oom" --type py -l

# Find files using update_vm_cpu_configuration
rg -rn "update_vm_cpu_configuration" --type py

# Find smoke tests that import from utilities/virt
rg -rn "pytest.mark.smoke" --type py -l | head -30

# Find smoke test files that import from utilities/virt
rg -rn "from utilities.virt import|from utilities import virt" --type py -l | head -30

Length of output: 1912


🏁 Script executed:

#!/bin/bash
# Find smoke test files that also import from utilities/virt
comm -12 \
  <(rg -rn "pytest.mark.smoke" --type py -l | sort) \
  <(rg -rn "from utilities.virt import|from utilities import virt" --type py -l | sort)

# Check cpu_flags fixture usage
rg -rn "cpu_flags" --type py -n

# Look at the WSL2 test file
cat tests/virt/node/general/test_wsl2.py

# Look at the OOM test file
cat tests/virt/node/general/test_oom.py

Length of output: 10306


🏁 Script executed:

#!/bin/bash
# Get PR diff to find first changed line
gh pr diff 4746 --patch | head -60

# Also check smoke test files for cpu_flags/vm_n usage
rg -n "cpu_flags|vm_n" tests/virt/node/general/test_container_disk_vm.py 2>/dev/null || echo "No matches in container_disk_vm"
rg -n "cpu_flags|vm_n" tests/virt/cluster/common_templates/rhel/test_rhel_os_support.py 2>/dev/null || echo "No matches in rhel_os_support"

Length of output: 2519


🏁 Script executed:

#!/bin/bash
# Post inline review comment on the first changed line of utilities/virt.py (line 13, deepcopy import)
gh api \
  --method POST \
  repos/RedHatQE/openshift-virtualization-tests/pulls/4746/reviews \
  --field commit_id="06c02ec1a7452d8734dcaa53a613e2ccdc2be8fe" \
  --field event="COMMENT" \
  --field "comments[][path]=utilities/virt.py" \
  --field "comments[][line]=13" \
  --field "comments[][side]=RIGHT" \
  --field "comments[][body]=**Test Execution Plan**

- **Run smoke tests: False** _(No concrete dependency path found from any smoke test to the changed \`cpu_flags\`/\`n\` fixture handling; smoke test files \`test_container_disk_vm.py\` and \`test_rhel_os_support.py\` do not use \`cpu_flags\` or \`vm_n\`.)_

**Directly affected tests (must run):**
- \`tests/virt/node/general/test_wsl2.py::TestWSL2\` — regression target; uses \`vm_cpu_flags\` → \`VirtualMachineForTests(cpu_flags=...)\` → the now-deepcopied \`self.cpu_flags\`
- \`tests/virt/node/general/test_oom.py::test_vm_windows_oom\` — mutation source; sets \`cpu_cores=16, cpu_threads=1\` which previously polluted the session-scoped fixture

**Secondary (use \`n\`/\`cpu_flags\` param on \`VirtualMachineForTests\`):**
- \`tests/virt/node/node_labeller/cpu_features/test_vm_with_cpu_flag.py\`
- \`tests/virt/node/node_labeller/cpu_features/test_vm_with_cpu_features.py\`"

Length of output: 1735


@rnetser
Copy link
Copy Markdown
Collaborator

rnetser commented May 5, 2026

/approve
/lgtm

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.

5 participants