Skip to content

Fix module-level logging in boltzmann example and add AST scan test - #3938

Closed
Niharika21-bisht wants to merge 8 commits into
mesa:mainfrom
Niharika21-bisht:fix-logging-issue
Closed

Niharika21-bisht wants to merge 8 commits into
mesa:mainfrom
Niharika21-bisht:fix-logging-issue

Conversation

@Niharika21-bisht

Copy link
Copy Markdown

Note

Use this template for bug fixes only. For enhancements/new features, use the feature template and get maintainer approval in an issue/discussion before opening a PR.

Pre-PR Checklist

  • This PR is a bug fix, not a new feature or enhancement.

Summary

Fixed a bug where importing the Boltzmann example app disabled MESA log propagation process-wide. Removed the offending module-level logging call and added a static AST scan test to prevent future regressions.

Bug / Issue

Fixes #3935.
Importing 'mesa/examples/basic/boltzmann_wealth_model/app.py'called 'log_to_stderr(INFO)' at the module level. Because this defaults to 'propagate=False' on the MESA root logger, it disabled log propagation for the rest of the process, breaking pytest's 'caplog' fixture in subsequent tests.

Implementation

  • Removed the module-level 'log_to_stderr(INFO)' call and its corresponding import from 'mesa/examples/basic/boltzmann_wealth_model/app.py'.

Testing

  • Added a new test 'test_no_module_level_logging_in_examples' in 'tests/test_mesa_logging.py'.
  • This test statically scans the AST of all Python files in the 'mesa/examples/' directory to assert that forbidden module-level logging configurations (like 'log_to_stderr', 'log_to_file', or 'basicConfig') are not present.

Additional Notes

As discussed in the issue, an import-based test was too slow, so the AST scan approach was used as it runs in just a few seconds and provides a robust guard against this recurring.

@github-actions github-actions Bot added example Changes the examples or adds to them. testing Release notes label labels Oct 13, 2026
@github-actions

Copy link
Copy Markdown

Performance benchmarks:

Model Size Init time [95% CI] Run time [95% CI]
BoltzmannWealth small 🟢 -4.5% [-5.2%, -3.8%] 🔵 +1.2% [+1.0%, +1.5%]
BoltzmannWealth large 🟢 -4.5% [-5.2%, -3.8%] 🟢 -5.0% [-6.1%, -3.9%]
Schelling small 🔵 -1.3% [-2.3%, -0.4%] 🔵 -0.0% [-0.8%, +0.8%]
Schelling large 🔵 +1.5% [+0.8%, +2.2%] 🔵 +4.5% [+1.4%, +8.4%]
WolfSheep small 🔵 +2.2% [+1.5%, +2.9%] 🔵 +1.3% [-2.6%, +5.4%]
WolfSheep large 🔵 -0.2% [-1.1%, +0.8%] 🔵 +1.8% [+0.6%, +3.1%]
SugarscapeG1mt small 🔵 +3.9% [+2.6%, +5.2%] 🔵 +1.8% [-0.1%, +3.6%]
SugarscapeG1mt large 🔵 -0.4% [-2.9%, +2.0%] 🔵 +0.4% [-0.9%, +1.6%]
BoidFlockers small 🔵 -2.7% [-3.0%, -2.4%] 🔵 -1.1% [-1.5%, -0.7%]
BoidFlockers large 🔵 +0.1% [-0.7%, +1.0%] 🔵 -0.3% [-0.7%, +0.0%]
MultiLevelAllianceModel small 🔴 +10.9% [+9.6%, +12.4%] 🔵 +1.6% [+1.0%, +2.3%]
MultiLevelAllianceModel large 🔴 +4.7% [+3.4%, +5.8%] 🔴 +15.2% [+11.0%, +18.7%]

@Niharika21-bisht

Copy link
Copy Markdown
Author

Hi! I noticed the build / examples check failed, but the error (ValueError: sequence of length 3 does not match the number of agents (20) in VirusAntibodyModel) seems completely unrelated to my logging changes. Let me know if I need to do anything else!

@dietcoke-17 dietcoke-17 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.

Fix the codecov fails diff is too low and pre commit error

@lahari936

Copy link
Copy Markdown
Contributor

Thanks for picking this up, and the AST scan looks good.

On the three checks — one of them is upstream, two are yours and both are quick:

examples — upstream, nothing to do. It fails identically on plain main: run 37892641437 on 5451086f gives the same FAILED test_model_steps[VirusAntibodyModel], 1 failed / 24 passed. mesa/mesa-examples#496 fixes it, so this check should go green on its own once that lands.

pre-commit.ci — not Vale. Vale is in the ci: skip: list at the top of .pre-commit-config.yaml, and it only selects .md/.rst/.txt anyway, so it never looked at your files. The failing hook is ruff check, with four errors, all in tests/test_mesa_logging.py:

  • D205 line 75 — the docstring needs a blank line between the summary line and the description.
  • B007 line 83 — dirs is unused in for root, dirs, files in os.walk(...); rename it _dirs.
  • B011 lines 99 and 107 — assert False is flagged because python -O strips assert, so the check would silently vanish. Ruff wants raise AssertionError(...) instead.

ruff check tests/test_mesa_logging.py locally reproduces all four.

codecov/patch — this one is a consequence of the test's shape rather than a separate problem. Both assert False branches only execute when the scan finds an offender, which it never does once the fix is in, so those added lines report as uncovered and drag patch coverage down. Note codecov/project passes; it's only the patch metric.

Collecting offenders and asserting once at the end fixes B011 and the coverage flag together, since there's no never-taken branch left:

offenders = []
for path in sorted(examples_dir.rglob("*.py")):
    tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
    for node in tree.body:  # module level only
        if not isinstance(node, ast.Expr) or not isinstance(node.value, ast.Call):
            continue
        func = node.value.func
        name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "")
        if name in forbidden_calls:
            offenders.append(f"{path.relative_to(examples_dir).as_posix()}:{node.lineno}: {name}()")

assert not offenders, (
    "example modules must not configure logging at import time: " + ", ".join(offenders)
)

Path.rglob also drops the os import and the os.walk triple, which takes B007 with it.

Two small things worth considering, take or leave:

  • Adding dictConfig to forbidden_calls alongside basicConfig — same hazard, and it costs nothing.
  • Dropping the except SyntaxError: continue. If a file under mesa/examples/ doesn't parse, that's worth failing on rather than skipping quietly.

Nice catch on reporting the CI state clearly rather than just pushing and hoping — made this easy to look at.

@Niharika21-bisht

Copy link
Copy Markdown
Author

Thanks for the detailed review and suggestions, @lahari936 and @dietcoke-17!

I have pushed the updates to fix the ruff pre-commit errors and the codecov/patch coverage dip using the suggested offenders list approach. The dictConfig has also been added to the forbidden calls list.

It looks like the only remaining failing check is the build / examples one, which as noted earlier is an upstream issue.

Let me know if there is anything else needed from my end to get this merged!

@lahari936

Copy link
Copy Markdown
Contributor

Nice, the offenders-list change did the job — codecov/patch is green now, and dictConfig is a good addition.

Small correction on the remaining state though: there are still two failing checks, not one. pre-commit.ci is also red, down to a single trivial error:

D415  First line should end with a period, question mark, or exclamation point
  --> tests/test_mesa_logging.py:74:5

The summary line of test_no_module_level_logging_in_examples()'s docstring just needs closing punctuation. One character and the hook goes green.

ruff check tests/test_mesa_logging.py reproduces it locally if you want to confirm before pushing.

The examples failure is the upstream one and is not yours — mesa/mesa-examples#496 fixes it at creation time, and mesa/mesa-examples#498 covers the duplication half.

@quaquel quaquel added the bug Release notes label label Oct 20, 2026
@quaquel

quaquel commented Oct 26, 2026 •

Copy link
Copy Markdown
Member

The reason this logging statement as in the example was to do just that: show how logging can be used with your own models. Removing the statement also fully removes any example on how to use logging. So, I am not in favor of this PR.

I am closing this PR in favor of first agreeing on a direction in the associated issue.

@quaquel quaquel closed this Oct 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Release notes label example Changes the examples or adds to them. testing Release notes label

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Importing the Boltzmann example app disables MESA log propagation, breaking caplog in later tests

4 participants