Skip to content

Implement more warnings#7008

Merged
youknowone merged 1 commit intoRustPython:mainfrom
youknowone:warnings
Feb 5, 2026
Merged

Implement more warnings#7008
youknowone merged 1 commit intoRustPython:mainfrom
youknowone:warnings

Conversation

@youknowone
Copy link
Member

@youknowone youknowone commented Feb 5, 2026

Summary by CodeRabbit

  • New Features

    • Support for PYTHONWARNINGS environment variable to configure warning options.
    • New runtime accessors and lock APIs for the warnings subsystem.
  • Improvements

    • Expanded and more robust warning handling (filters, registry, categories, skip-prefix stack trimming).
    • Cleaner stack-frame traversal for external frames.
    • Minor message-handling and formatting refinements.
  • Chores

    • Dictionary token reorganization and de-duplication.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 5, 2026

📝 Walkthrough

Walkthrough

Refactors and expands the warnings subsystem: adds VM-level warning state and lock APIs, broadens warn/warn_explicit to accept PyObject messages, adds PYTHONWARNINGS parsing, simplifies frame traversal, and updates call sites to pass message.into() conversions; many changes affect warn routing, registry, and filter matching.

Changes

Cohort / File(s) Summary
Warnings core & state
crates/vm/src/warn.rs, crates/vm/src/stdlib/warnings.rs, crates/vm/src/vm/context.rs
Introduce WarningsState public fields (filters, once_registry, default_action, filters_version, context_var), add lock APIs (acquire/release, filters_mutated), implement filter-matching and warn_with_skip, expose _warnings module accessors, and add const names for new keys.
API surface & call sites
crates/stdlib/src/_asyncio.rs, crates/stdlib/src/socket.rs, crates/vm/src/coroutine.rs, crates/vm/src/stdlib/ast/python.rs, crates/vm/src/stdlib/ast/string.rs
Update warn call sites and deprecation message construction to pass messages as PyObject (.into()), reflow minor chains for readability; no behavioral changes.
Frame traversal
crates/vm/src/frame.rs, crates/vm/src/warn.rs
Simplify next_external_frame traversal and add next_external_frame_with_skip / is_filename_to_skip to support skip_file_prefixes during stack walking.
Settings / env parsing
src/settings.rs
Parse PYTHONWARNINGS environment variable and append entries to Settings.warnoptions before CLI processing.
Misc (dictionary)
.cspell.dict/python-more.txt
Reorganized and de-duplicated dictionary tokens; minor insert/remove adjustments.

Sequence Diagram(s)

sequenceDiagram
    participant Env as Settings / Env
    participant WarnAPI as warn() / warn_explicit
    participant FrameWalk as Frame Walker
    participant Filter as Filter Matcher
    participant Registry as once_registry
    participant Show as call_show_warning / _showwarnmsg

    Env->>WarnAPI: provide message, category, skip_file_prefixes
    WarnAPI->>FrameWalk: walk stack (skip internals/prefixes)
    FrameWalk-->>WarnAPI: calling context (filename, lineno, module)
    WarnAPI->>Filter: evaluate filters for category & message
    Filter-->>WarnAPI: action (error/ignore/once/always/default/module)
    alt error
        WarnAPI->>Env: raise as exception
    else once
        WarnAPI->>Registry: check/record
        Registry-->>WarnAPI: already_warned? / recorded
        alt not recorded
            WarnAPI->>Show: call_show_warning with text & instance
            Show-->>Env: emit via _showwarnmsg
        end
    else emit
        WarnAPI->>Show: call_show_warning
        Show-->>Env: emit via _showwarnmsg
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰
I hopped through warnings, soft and bright,
Filters lined up, locks held tight,
Frames now skip the rabbit holes,
Messages flow as coherent goals,
A tidy burrow for each light. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 inconclusive)
Check name Status Explanation Resolution
Title check ❓ Inconclusive The title 'Implement more warnings' is vague and does not clearly convey the specific nature of the changes in this pull request. Consider a more descriptive title that reflects the main objective, such as 'Enhance warnings module with filter management and context support' or 'Add warning filters and lock management to stdlib'.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed Docstring coverage is 87.18% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

@youknowone youknowone marked this pull request as ready for review February 5, 2026 13:58
Copy link
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: 2

🤖 Fix all issues with AI agents
In @.cspell.dict/python-more.txt:
- Around line 102-103: The dictionary contains a duplicate entry "getweakrefs"
on consecutive lines; remove the redundant line so only a single "getweakrefs"
entry remains (i.e., keep one occurrence and delete the duplicate to ensure
unique entries).

In `@crates/vm/src/warn.rs`:
- Around line 88-94: The release_lock implementation can underflow because load
+ fetch_sub races; replace the two-step logic in release_lock to an atomic
compare-and-swap loop (e.g., using AtomicUsize::fetch_update or a CAS loop) on
self.lock_count: read current, if zero return false, otherwise attempt to set
current - 1 and retry on contention; return true only when the decrement
succeeded so concurrent releases cannot drive the counter to usize::MAX.

Comment on lines 102 to +103
getweakrefs
getweakrefs
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Remove duplicate entry.

The term "getweakrefs" appears twice on consecutive lines. Dictionary files should contain unique entries only.

🔧 Proposed fix
 getweakrefcount
-getweakrefs
 getweakrefs
 getwindowsversion
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
getweakrefs
getweakrefs
getweakrefcount
getweakrefs
getwindowsversion
🤖 Prompt for AI Agents
In @.cspell.dict/python-more.txt around lines 102 - 103, The dictionary contains
a duplicate entry "getweakrefs" on consecutive lines; remove the redundant line
so only a single "getweakrefs" entry remains (i.e., keep one occurrence and
delete the duplicate to ensure unique entries).

Comment on lines +88 to +94
pub fn release_lock(&self) -> bool {
let prev = self.lock_count.load(Ordering::SeqCst);
if prev == 0 {
return false;
}
self.lock_count.fetch_sub(1, Ordering::SeqCst);
true
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Avoid lock_count underflow on concurrent release.
load + fetch_sub can race, causing an underflow to usize::MAX if two releases happen around the same time. Use fetch_update/CAS to make the decrement conditional.

Proposed fix
-    pub fn release_lock(&self) -> bool {
-        let prev = self.lock_count.load(Ordering::SeqCst);
-        if prev == 0 {
-            return false;
-        }
-        self.lock_count.fetch_sub(1, Ordering::SeqCst);
-        true
-    }
+    pub fn release_lock(&self) -> bool {
+        self.lock_count
+            .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |v| {
+                if v == 0 { None } else { Some(v - 1) }
+            })
+            .is_ok()
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
pub fn release_lock(&self) -> bool {
let prev = self.lock_count.load(Ordering::SeqCst);
if prev == 0 {
return false;
}
self.lock_count.fetch_sub(1, Ordering::SeqCst);
true
pub fn release_lock(&self) -> bool {
self.lock_count
.fetch_update(Ordering::SeqCst, Ordering::SeqCst, |v| {
if v == 0 { None } else { Some(v - 1) }
})
.is_ok()
}
🤖 Prompt for AI Agents
In `@crates/vm/src/warn.rs` around lines 88 - 94, The release_lock implementation
can underflow because load + fetch_sub races; replace the two-step logic in
release_lock to an atomic compare-and-swap loop (e.g., using
AtomicUsize::fetch_update or a CAS loop) on self.lock_count: read current, if
zero return false, otherwise attempt to set current - 1 and retry on contention;
return true only when the decrement succeeded so concurrent releases cannot
drive the counter to usize::MAX.

@github-actions
Copy link
Contributor

github-actions bot commented Feb 5, 2026

📦 Library Dependencies

The following Lib/ modules were modified. Here are their dependencies:

[ ] lib: cpython/Lib/site.py
[ ] lib: cpython/Lib/_sitebuiltins.py
[ ] test: cpython/Lib/test/test_site.py (TODO: 4)

dependencies:

  • site (native: _io, builtins, errno, sys)
    • _sitebuiltins
    • _sitebuiltins (native: sys)
    • stat
    • os

dependent tests: (1 tests)

  • site: test_site

[x] lib: cpython/Lib/warnings.py
[x] lib: cpython/Lib/_py_warnings.py
[ ] test: cpython/Lib/test/test_warnings (TODO: 17)

dependencies:

  • warnings

dependent tests: (48 tests)

  • warnings: test_argparse test_asyncio test_buffer test_builtin test_codecs test_codeop test_coroutines test_ctypes test_decimal test_descr test_fnmatch test_fstring test_genericpath test_glob test_global test_grammar test_gzip test_hashlib test_hmac test_importlib test_inspect test_io test_itertools test_logging test_ntpath test_os test_pickle test_posix test_pty test_pyclbr test_random test_re test_runpy test_set test_socket test_sqlite3 test_str test_string_literals test_support test_sys test_tempfile test_threading test_typing test_unicode_file_functions test_unittest test_unparse test_xml_etree test_zipimport

Legend:

  • [+] path exists in CPython
  • [x] up-to-date, [ ] outdated

@youknowone youknowone changed the title Fix more warnings Implement more warnings Feb 5, 2026
@youknowone youknowone merged commit 19db8d0 into RustPython:main Feb 5, 2026
13 of 14 checks passed
@youknowone youknowone deleted the warnings branch February 5, 2026 22:45
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant