Skip to content

test: run example scripts in subprocesses so joblib workers can pickle - #90

Merged
endolith merged 2 commits into
masterfrom
fix/test-run-subprocess
Aug 6, 2026
Merged

test: run example scripts in subprocesses so joblib workers can pickle#90
endolith merged 2 commits into
masterfrom
fix/test-run-subprocess

Conversation

@kilo-code-bot

@kilo-code-bot kilo-code-bot Bot commented Aug 4, 2026

Copy link
Copy Markdown
Contributor

Problem

The example tests run the scripts with runpy.run_path, which gives them the module name '<run_path>'. When the script calls Parallel(backend='loky'), loky workers can't unpickle the batch function and CI fails with ModuleNotFoundError: No module named '<run_path>'. This only shows up with real parallelism, so it wasn't caught locally.

What this PR changes

  • Run each script in a subprocess as a real __main__ (the way joblib/loky expects), appending a pickle.dump(table, ...) so the test still reads the computed table directly instead of parsing printed output.
  • Assert each table is non-empty and every reference row has the expected number of values (the old [:len(expected)] silently truncated extra columns).

Also supersedes #89 (its length-assertion change is folded in here).

Tests

The example tests themselves (pytest -m slow); verified the two Weber scripts pass with the new mechanism, and CI now exercises the real loky parallel path.

Summary by CodeRabbit

  • Tests
    • Improved example validation by running scripts in isolated processes.
    • Added timeout and error detection for clearer test failures.
    • Added temporary-output handling and direct validation of serialized tables.
    • Tests now require non-empty results, exact row lengths, and complete row matches.
    • Removed in-process execution and shared environment changes to improve test reliability.

@what-the-diff

what-the-diff Bot commented Aug 4, 2026

Copy link
Copy Markdown

PR Summary

  • Improved Documentation for Test Procedure
    The instructions related to executing subprocesses have been thoroughly revised for better understanding.

  • Import Optimization
    The imports that were not in use (contextlib, io, and runpy) have been removed. This makes the code cleaner and easier to navigate.

  • Added New Modules
    Two new modules, pickle and subprocess, have been incorporated. These modules streamline the execution of scripts and preservation of data, enhancing our code's efficiency.

  • Function Update for Script Execution
    The _run function has been altered to execute scripts in a subprocess and save the output using pickle module. This modification streamlines the script execution process and alleviates load on the main process.

  • Function Update for Extracting Data
    The _table_rows function has been updated to directly accept the table argument. This eliminates an unnecessary step of extracting the table from globals, making the function more efficient.

  • Improved Testing Method
    The test_example function has been updated to incorporate a temporary path for the _run function. It also includes new assertions to validate the results more rigorously. These changes facilitate more accurate and reliable testing.

@coderabbitai

coderabbitai Bot commented Aug 4, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 49e62b7a-b283-4762-bad6-e2133025a832

📥 Commits

Reviewing files that changed from the base of the PR and between c42770e and e088bcd.

📒 Files selected for processing (1)
  • tests/test_examples.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/test_examples.py

📝 Walkthrough

Walkthrough

The example tests now run each script in an isolated subprocess. They serialize and reload the computed table, enforce non-empty output and exact row lengths, and compare complete rows.

Changes

Example test execution

Layer / File(s) Summary
Subprocess execution and table validation
tests/test_examples.py
The tests replace in-process execution with temporary subprocess scripts, pickle-based table transfer, environment isolation, timeout and failure checks, and stricter table and row validation.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

  • endolith/elsim#65: This PR also substantially modifies tests/test_examples.py to execute and validate example scripts.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: running example tests in subprocesses to support joblib worker pickling.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/test-run-subprocess

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

@codecov

codecov Bot commented Aug 4, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 96.37%. Comparing base (a261024) to head (e088bcd).

Additional details and impacted files
@@           Coverage Diff           @@
##           master      #90   +/-   ##
=======================================
  Coverage   96.37%   96.37%           
=======================================
  Files          17       17           
  Lines         496      496           
=======================================
  Hits          478      478           
  Misses         18       18           
Flag Coverage Δ
no-numba 95.76% <ø> (ø)
numba 88.10% <ø> (ø)

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

☔ View full report in Codecov by Harness.
📢 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
tests/test_examples.py (2)

132-133: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Keep the child traceback in test failures.

capture_output=True stores child output, but this helper does not report CalledProcessError.stdout or CalledProcessError.stderr. A failing example therefore exposes only the exit status. Preserve the captured output in the failure message or let the child inherit its output streams.

Suggested failure handling
-    subprocess.run([sys.executable, str(variant)], env=env,
-                   capture_output=True, timeout=1200, check=True)
+    try:
+        subprocess.run([sys.executable, str(variant)], env=env,
+                       capture_output=True, text=True,
+                       timeout=1200, check=True)
+    except subprocess.CalledProcessError as exc:
+        pytest.fail(f'{name} failed:\n{exc.stderr}\n{exc.stdout}')
🤖 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 `@tests/test_examples.py` around lines 132 - 133, Update the subprocess
invocation in the example-test helper to retain child stdout and stderr in
failures: either report CalledProcessError.stdout and CalledProcessError.stderr
when check=True raises, or stop capturing output so the child traceback is
visible directly. Preserve the existing timeout and successful-execution
behavior.

131-131: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Preserve the inherited PYTHONPATH.

Line 131 replaces the caller's PYTHONPATH with only EXAMPLES. A source checkout or CI job that uses PYTHONPATH for project packages can fail to import those packages in the child process. Prepend EXAMPLES and retain existing entries, unless repository setup guarantees an installed package.

Suggested environment construction
-    env = {**os.environ, 'MPLBACKEND': 'Agg', 'PYTHONPATH': str(EXAMPLES)}
+    inherited_pythonpath = os.environ.get('PYTHONPATH')
+    pythonpath = os.pathsep.join(
+        path for path in (str(EXAMPLES), inherited_pythonpath) if path)
+    env = {**os.environ, 'MPLBACKEND': 'Agg', 'PYTHONPATH': pythonpath}
🤖 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 `@tests/test_examples.py` at line 131, Update the environment construction
around the env assignment to prepend EXAMPLES to any inherited PYTHONPATH
instead of replacing it. Preserve all existing PYTHONPATH entries, using the
platform’s path separator when joining them, while retaining the MPLBACKEND
value and other inherited environment variables.
🤖 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 `@tests/test_examples.py`:
- Around line 8-9: Update the documentation in tests/test_examples.py to
reference TOLERANCES separately from REFERENCE_VALUES, directing maintainers to
the correct definition for tolerance values while preserving the
reference-values guidance.

---

Nitpick comments:
In `@tests/test_examples.py`:
- Around line 132-133: Update the subprocess invocation in the example-test
helper to retain child stdout and stderr in failures: either report
CalledProcessError.stdout and CalledProcessError.stderr when check=True raises,
or stop capturing output so the child traceback is visible directly. Preserve
the existing timeout and successful-execution behavior.
- Line 131: Update the environment construction around the env assignment to
prepend EXAMPLES to any inherited PYTHONPATH instead of replacing it. Preserve
all existing PYTHONPATH entries, using the platform’s path separator when
joining them, while retaining the MPLBACKEND value and other inherited
environment variables.
🪄 Autofix

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: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 2a5e2bf1-c518-46c1-993d-5bbd05d73309

📥 Commits

Reviewing files that changed from the base of the PR and between 6e08e9e and be58012.

📒 Files selected for processing (1)
  • tests/test_examples.py

Comment thread tests/test_examples.py
Running the scripts with runpy.run_path gives them the module name
'<run_path>', which loky workers cannot import, breaking the parallel
path in CI (ModuleNotFoundError: No module named '<run_path>').
Run each script in a subprocess as a real __main__ instead, and have it
dump its table to a pickle the test reads back, so values are still
checked directly without parsing printed output.

Also assert each table is non-empty and every reference row has the
expected number of values, instead of silently truncating.
@endolith
endolith force-pushed the fix/test-run-subprocess branch from be58012 to c42770e Compare August 6, 2026 03:51
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 `@tests/test_examples.py`:
- Around line 147-155: Add a concise docstring to the test_example function
documenting that it verifies non-empty output and complete reference rows, and
that these checks prevent silent truncation; do not alter the test logic.
🪄 Autofix

✅ Autofix completed


ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: eccfc325-418b-4edd-bbeb-4bc2cd9d85d2

📥 Commits

Reviewing files that changed from the base of the PR and between a261024 and c42770e.

📒 Files selected for processing (1)
  • tests/test_examples.py

Comment thread tests/test_examples.py
@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown

Fixes Applied Successfully

Fixed 1 file(s) based on 1 unresolved review comment.

Files modified:

  • tests/test_examples.py

Commit: 5e224934cf26dbe16703b68d2c472d133dcd8630

The changes have been pushed to the fix/test-run-subprocess branch.

Time taken: 2m 19s

Add a docstring explaining that the example scripts are run in a subprocess
and their computed table checked against REFERENCE_VALUES within TOLERANCES,
and that the non-empty/equal-length assertions make silent output truncation
fail with a clear message.

Co-authored-by: opencode <opencode@anomalyco.ai>
@endolith
endolith force-pushed the fix/test-run-subprocess branch from 5e22493 to e088bcd Compare August 6, 2026 04:08
@endolith
endolith merged commit 0ec02cd into master Aug 6, 2026
16 checks passed
@endolith
endolith deleted the fix/test-run-subprocess branch August 6, 2026 04:12
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