Skip to content

Simplify tests/helpers/maturin.py: inline pin checks, consolidate wheel snapshot (#97, #99) - #240

Open
leynos wants to merge 4 commits into
mainfrom
simplify-maturin-helper
Open

Simplify tests/helpers/maturin.py: inline pin checks, consolidate wheel snapshot (#97, #99)#240
leynos wants to merge 4 commits into
mainfrom
simplify-maturin-helper

Conversation

@leynos

@leynos leynos commented Jul 28, 2026

Copy link
Copy Markdown
Owner

Summary

tests/helpers/maturin.py had grown to 394 lines / 15 definitions while serving a single consumer, cuprum/unittests/test_maturin_build.py — the over-extraction flagged in #97 and #99. This PR inlines the pin-synchronisation logic into that sole consumer and consolidates the wheel-snapshot machinery.

Changes

  • Inline pin-reading into the consumer. read_expected_maturin_version, read_maturin_pins, read_manylinux_aarch64_container_ref, workflow_uses_manylinux_aarch64_container_ref, _require_pin_match, and all five pin regexes now live as private helpers in test_maturin_build.py. They have exactly one caller each.
  • Consolidate wheel-snapshot parsing 6 → 3 functions. _header_value, _locate_dist_info_wheel, and _parse_wheel_header are folded into wheel_build_snapshot/_parse_metadata, leaving three primary parsing functions (wheel_build_snapshot, _parse_metadata, _normalise_wheel_entry) as Simplify tests/helpers/maturin.py: consolidate 12 functions into 2–3 and defer abstraction until second consumer exists #99 asks.
  • Fold _maturin_module_available into toolchain_available.
  • Document the reuse policy (defer re-externalisation until a second concrete consumer exists) in the module docstring.

The retained wheel build/snapshot machinery wraps subprocess and zipfile introspection that does not inline cleanly, so per #97 it stays as a minimal helper.

Result: helper drops to 218 lines / 6 definitions.

Why the entry-normalisation is kept

Every _normalise_wheel_entry branch — the .dist-info suffixes, /sboms/, and the .cpython-<platform>.so extension module — is exercised by the test_maturin_wheel_build_snapshot syrupy snapshot, which runs across the wheel-build matrix. None is speculative, and removing any would change verified output.

Validation

  • test_maturin_wheel_build_snapshot passes with byte-identical snapshot output (behaviour preserved).
  • Full gates green: make check-fmt, make lint (ruff, interrogate 100%, pylint 10.00/10), make test (755 passed / 47 skipped; Rust nextest 57/57).

Closes #97
Closes #99

🤖 Generated with Claude Code

Summary by Sourcery

Inline maturin pin-synchronisation helpers into the maturin build tests and slim down the shared maturin helper to focus on wheel build/snapshot introspection.

Enhancements:

  • Fold maturin module detection into the Rust toolchain availability check to reduce indirection.
  • Simplify wheel metadata parsing by inlining header-extraction helpers and consolidating WHEEL/METADATA handling into the main snapshot function.

Documentation:

  • Document the reuse policy for the maturin test helper module, clarifying that new shared helpers should only be added when there is more than one consumer.

Tests:

  • Move maturin pin and manylinux container regexes and readers into private helpers within test_maturin_build, keeping the pin-synchronisation logic local to its only consumer.

tests/helpers/maturin.py had grown to 394 lines / 15 defs serving one
consumer (cuprum/unittests/test_maturin_build.py). Per #97 and #99:

- Inline all pin-reading logic (read_expected_maturin_version,
  read_maturin_pins, read_manylinux_aarch64_container_ref,
  workflow_uses_manylinux_aarch64_container_ref, _require_pin_match) and
  its regexes directly into the sole consumer as private helpers.
- Consolidate wheel-snapshot parsing from six functions (_header_value,
  _parse_metadata, _normalise_wheel_entry, _locate_dist_info_wheel,
  _parse_wheel_header, wheel_build_snapshot) to three by folding the
  single-purpose extractors into wheel_build_snapshot and _parse_metadata.
- Fold _maturin_module_available into toolchain_available.
- Document the defer-until-second-consumer policy in the module docstring.

The wheel entry-normalisation is retained unchanged: every branch
(dist-info suffixes, /sboms/, the .cpython-<platform>.so extension) is
exercised by the test_maturin_wheel_build_snapshot syrupy snapshot across
the build matrix, so none is speculative. Snapshot output is byte-
identical. Helper drops to 218 lines / 6 defs.

Closes #97
Closes #99

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
@sourcery-ai

sourcery-ai Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Simplifies the maturin test helper by inlining pin- and workflow-related logic into its sole test consumer and collapsing wheel snapshot parsing into fewer, more cohesive functions, while tightening the toolchain availability check and documenting reuse policy.

File-Level Changes

Change Details Files
Inline maturin pin and manylinux-container checks into the maturin build tests, turning the shared helper into a focused wheel/snapshot helper.
  • Move maturin pin regexes and manylinux container regexes from the helper module into test_maturin_build as private test-local constants.
  • Reimplement pin-reading and manylinux container helper functions directly in test_maturin_build.py with repo-relative file reads.
  • Update tests to call the new private helpers instead of the removed functions from tests.helpers.maturin.
cuprum/unittests/test_maturin_build.py
tests/helpers/maturin.py
Collapse wheel metadata parsing into fewer functions and simplify metadata extraction.
  • Remove the generic header_value helper and inline single-valued header extraction inside _parse_metadata.
  • Change _parse_metadata to pull first values directly from the headers dict while still sorting multi-valued headers.
  • Update the docstring for _parse_metadata to clarify it parses METADATA headers specifically.
tests/helpers/maturin.py
Consolidate WHEEL header parsing and archive inspection into wheel_build_snapshot.
  • Inline _locate_dist_info_wheel logic into wheel_build_snapshot when locating the .dist-info/WHEEL entry.
  • Inline _parse_wheel_header logic into wheel_build_snapshot to derive generator and Root-Is-Purelib values from the WHEEL payload.
  • Keep layout normalisation via _normalise_wheel_entry but reuse the inlined metadata to build the snapshot structure.
tests/helpers/maturin.py
Tighten the Rust toolchain availability check and clarify helper module intent.
  • Merge _maturin_module_available into toolchain_available, handling ImportError defensively and returning a single boolean.
  • Adjust the toolchain_available docstring to mention both Rust toolchain and maturin module availability.
  • Add a module-level docstring explaining that only wheel build/snapshot helpers remain here and that further extraction should wait for a second consumer.
tests/helpers/maturin.py

Assessment against linked issues

Issue Objective Addressed Explanation
#97 Inline the maturin pin-collection and version-expectation logic from tests/helpers/maturin.py into cuprum/unittests/test_maturin_build.py, leaving tests/helpers/maturin.py as a minimal helper module.
#97 Simplify tests/helpers/maturin.py by removing speculative platform-variability normalisation and over-general wheel parsing, retaining only the minimal wheel_build_snapshot machinery and its directly required helpers.
#97 Document the reuse strategy for test helpers in docs/developers-guide.md before any future re-externalisation of shared helpers. The PR documents the reuse policy in the tests/helpers/maturin.py module docstring, but does not add or modify any content in docs/developers-guide.md as explicitly requested in the issue.
#99 Inline maturin pin-reading and workflow pin-synchronisation logic from tests/helpers/maturin.py directly into its sole consumer cuprum/unittests/test_maturin_build.py.
#99 Consolidate wheel snapshot parsing helpers in tests/helpers/maturin.py into 2–3 primary functions, reducing over-extraction while preserving behaviour.
#99 Remove or avoid speculative, unexercised platform-variability normalisation from tests/helpers/maturin.py and document that further abstraction should be deferred until a second concrete consumer exists.

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Summary

  • Inlined maturin and manylinux pin synchronisation checks into test_maturin_build.py, their sole consumer.
  • Simplified tests/helpers/maturin.py to retain wheel-building and snapshot utilities, including consolidated wheel member parsing.
  • Added coverage for missing wheel metadata members while preserving byte-identical snapshots.
  • Documented the helper reuse boundary: re-extract shared helpers only when a second concrete consumer exists.
  • No production-code changes; formatting, linting, documentation, and test gates pass.

Walkthrough

Changes

Inline maturin and manylinux pin validation in the build tests, refactor wheel metadata and archive-member parsing, and document the narrower shared-helper boundary. Add coverage for wheels missing required metadata members.

Maturin helper simplification

Layer / File(s) Summary
Localise maturin pin validation
cuprum/unittests/test_maturin_build.py
Inline regex-based readers for maturin and manylinux pins, update synchronisation tests, and validate missing wheel metadata members.
Refine wheel snapshot machinery
tests/helpers/maturin.py, docs/developers-guide.md
Restrict the helper to wheel builds and snapshots, refactor metadata/member parsing, inline toolchain checks, and document the reuse boundary.

Possibly related PRs

Suggested labels: Issue

Poem

Pins find their home in tests tonight,
Wheels keep their snapshots neat and bright.
Metadata sorts in tidy rows,
Shared helpers shed unused clothes.
Rust and maturin march in tune.

🚥 Pre-merge checks | ✅ 20
✅ Passed checks (20 passed)
Check name Status Explanation
Title check ✅ Passed The title matches the refactor scope and includes the linked issue numbers.
Description check ✅ Passed The description is clearly aligned with the maturin helper simplification and wheel snapshot refactor.
Linked Issues check ✅ Passed The changes inline the pin logic, reduce helper abstraction, and document reuse policy as required by #97 and #99.
Out of Scope Changes check ✅ Passed No unrelated changes stand out; the docs update and new wheel-member test both support the stated refactor.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Testing (Overall) ✅ Passed Accept: the new zip-archive failure test and the built-wheel snapshot test exercise real behaviour, not mocks or tautologies.
User-Facing Documentation ✅ Passed Treat this as PASS: the PR only refactors tests/helpers, and docs/users-guide.md already documents the maturin pin and native wheel workflow.
Developer Documentation ✅ Passed Docs/developers-guide.md now documents the new maturin helper boundary, reuse policy, and test roles; no locale, roadmap, or execplan gap found.
Module-Level Documentation ✅ Passed Both changed Python modules carry clear module docstrings; tests/helpers/maturin.py states its wheel-snapshot role and sole-consumer boundary.
Testing (Unit And Behavioural) ✅ Passed PASS: The suite adds a real wheel-build snapshot, boundary checks for missing METADATA/WHEEL, and local invariant tests with explicit error-path coverage.
Testing (Property / Proof) ✅ Passed This is a refactor with example-based assertions and a snapshot test; it does not introduce a new range invariant or proof assumption needing property/proof tooling.
Testing (Compile-Time / Ui) ✅ Passed No new compile-time behaviour needs trybuild; the wheel snapshot is focused, normalised, and paired with explicit semantic assertions.
Unit Architecture ✅ Passed Keep the split: query helpers only read files, commands stay explicit, and impure subprocess/zipfile work is fenced behind narrow test helpers.
Domain Architecture ✅ Passed Only test helper and developer-guide files changed; no domain or production modules were touched, so the domain boundary remains intact.
Observability ✅ Passed PASS: the PR only refactors test/helper code and docs; no production path or observability surface changed, and no logging, metrics, tracing, or alerts were added.
Security And Privacy ✅ Passed PASS: The refactor only moves maturin/wheel parsing into tests and docs; no secrets, auth changes, unsafe sinks, or sensitive-data exposure were added.
Performance And Resource Use ✅ Passed PASS: The only extra pass is a bounded zip-member membership check; file reads and snapshot parsing stay linear and small, with no hot-path growth.
Concurrency And State ✅ Passed Accept this: the PR stays synchronous, adds no shared mutable state or locks, and tests the new missing-METADATA and missing-WHEEL paths.
Architectural Complexity And Maintainability ✅ Passed Accept the refactor: it removes speculative indirection, keeps only the wheel-introspection seam, and documents the reuse boundary.
Rust Compiler Lint Integrity ✅ Passed No Rust files changed, and repository searches found no added #[allow(dead_code|unused_*)] or #[expect(dead_code)] suppressions.
✨ 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 simplify-maturin-helper

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

codescene-access[bot]

This comment was marked as outdated.

@sourcery-ai sourcery-ai Bot 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.

Hey - I've left some high level feedback:

  • In the pin-synchronisation helpers in test_maturin_build.py, pyproject.toml and the workflow/action YAML files are read multiple times within the same test run (e.g., _read_expected_maturin_version and _read_maturin_pins each re-open pyproject.toml), so consider caching these file contents per test module (e.g., via a small module-level cache or a fixture) to avoid redundant I/O and keep the helpers simpler.
  • In wheel_build_snapshot, the inline logic for locating the .dist-info/WHEEL entry and deriving the METADATA entry is now embedded directly in the function; if you intend to reuse this logic elsewhere, consider extracting a small internal helper (e.g., _dist_info_paths) to clarify the intent and make the error handling around missing WHEEL/METADATA entries easier to test and maintain.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In the pin-synchronisation helpers in `test_maturin_build.py`, `pyproject.toml` and the workflow/action YAML files are read multiple times within the same test run (e.g., `_read_expected_maturin_version` and `_read_maturin_pins` each re-open `pyproject.toml`), so consider caching these file contents per test module (e.g., via a small module-level cache or a fixture) to avoid redundant I/O and keep the helpers simpler.
- In `wheel_build_snapshot`, the inline logic for locating the `.dist-info/WHEEL` entry and deriving the `METADATA` entry is now embedded directly in the function; if you intend to reuse this logic elsewhere, consider extracting a small internal helper (e.g., `_dist_info_paths`) to clarify the intent and make the error handling around missing WHEEL/METADATA entries easier to test and maintain.

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6494aa38bf

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tests/helpers/maturin.py Outdated
codescene-access[bot]

This comment was marked as outdated.

Consolidating the wheel parsing pushed wheel_build_snapshot to a
cyclomatic complexity of 10 (threshold 9) and the module mean to 4.43
(threshold 4). Extract _read_wheel_members (archive read + member
lookup) and _parse_wheel_header (generator + Root-Is-Purelib), leaving
wheel_build_snapshot as a thin orchestrator. Behaviour and snapshot
output are unchanged; CodeScene health returns to 10.0.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
codescene-access[bot]

This comment was marked as outdated.

codescene-access[bot]

This comment was marked as outdated.

The developers guide still described tests/helpers/maturin.py as providing
shared helpers for the pin-contract tests, which is the opposite of the
boundary this branch implements: the pin checks are now private helpers in
cuprum/unittests/test_maturin_build.py and only the wheel build/snapshot
machinery remains shared.

Rewrite the section intro to state both halves of the split, name the
retained module's narrow scope, and record the defer-until-second-consumer
reuse policy the abstraction policy in AGENTS.md requires.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
codescene-access[bot]

This comment was marked as outdated.

@coderabbitai coderabbitai Bot added the Issue label Jul 28, 2026

@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: 4

🤖 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 `@docs/developers-guide.md`:
- Around line 1412-1415: Update the wheel builder scope description around
build_native_wheel_artifact, toolchain_available, and wheel_build_snapshot to
state that build_native_wheel_artifact uses the maturin module available to the
current Python interpreter rather than selecting a pinned version. Also describe
the pin check and snapshot generator assertion as the mechanisms enforcing
version alignment.

In `@tests/helpers/maturin.py`:
- Around line 164-178: In _read_wheel_members, validate that the derived
metadata_name appears in entry_names before calling archive.read(metadata_name).
Raise the documented AssertionError with the missing .dist-info/METADATA message
when absent, while preserving the existing read and decode flow when present.
- Around line 71-80: The public function toolchain_available in
tests/helpers/maturin.py (lines 71-80) needs a NumPy-style Returns section
documenting that it returns True only when cargo, rustc, and the maturin module
are available. Add the corresponding Returns section to the other changed public
function in tests/helpers/maturin.py (lines 204-208), documenting its stable
snapshot mapping for a wheel.
- Line 127: Update the changed docstrings in the relevant parsing helpers,
including the one describing RFC 2822 METADATA headers and the sections at the
referenced locations, to use Oxford -ize spellings: replace “normalised”,
“Normalise”, and “normalises” with “normalized”, “Normalize”, and “normalizes”
while preserving the existing documentation content.
🪄 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: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: c88aed4c-c59f-41bd-9c32-9cbed57e0797

📥 Commits

Reviewing files that changed from the base of the PR and between 302858c and 8b3df4a.

📒 Files selected for processing (3)
  • cuprum/unittests/test_maturin_build.py
  • docs/developers-guide.md
  • tests/helpers/maturin.py
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

  • leynos/shared-actions (auto-detected)
  • leynos/pylint-pypy-shim (auto-detected)
  • leynos/whitaker (auto-detected)

Comment thread docs/developers-guide.md Outdated
Comment thread tests/helpers/maturin.py
Comment thread tests/helpers/maturin.py Outdated
Comment thread tests/helpers/maturin.py
@pandalump

Copy link
Copy Markdown
Collaborator

The Testing (Unit And Behavioural) row came back Inconclusive ("placeholder | need evidence"), so I validated it myself, scoped to this PR. Recording the evidence rather than leaving the row to come back inconclusive next round.

What this PR changes. It is a pure refactor with no behaviour change: pin-reading logic moves from tests/helpers/maturin.py into its sole consumer cuprum/unittests/test_maturin_build.py as private helpers, and the wheel-snapshot parsing is consolidated. No production (cuprum/) code is touched — the diff is one test module, one test helper, and the developers guide.

Strongest evidence — the snapshot is byte-identical. test_maturin_wheel_build_snapshot builds a real release wheel and compares metadata, Root-Is-Purelib, generator, and the full normalised entry list against the stored .ambr. It passes unchanged, i.e. the refactor did not alter wheel_build_snapshot's observable output. That snapshot also exercises every branch of _normalise_wheel_entry (dist-info suffixes, /sboms/, and the .cpython-<platform>.so extension module), which is why none of them were removed as speculative.

Coverage of the changed surface. All 14 tests in the module pass, and every retained and inlined symbol is exercised:

Symbol Exercised by
build_native_wheel_artifact test_build_native_wheel_artifact_uses_locked_cargo_deps, ..._reports_maturin_stderr, snapshot test
MaturinBuildError test_build_native_wheel_artifact_reports_maturin_stderr
wheel_build_snapshot (+ _read_wheel_members, _parse_wheel_header, _parse_metadata, _normalise_wheel_entry) test_maturin_wheel_build_snapshot
toolchain_available snapshot test skip guard
_read_maturin_pins test_maturin_pins_are_synchronized
_read_expected_maturin_version test_installed_maturin_matches_expected_pin, snapshot test
_read_manylinux_aarch64_container_ref test_manylinux_aarch64_container_is_pinned_to_sha256
_workflow_uses_manylinux_aarch64_container_ref test_manylinux_aarch64_container_is_referenced_by_build_step
pin/container regexes 5 parametrised rejection cases + 2 regex-negative tests

Gates. make check-fmt, make lint (ruff, interrogate 100%, pylint 10.00/10), make test (full suite plus Rust nextest), make markdownlint, and make nixie are all green.

No new behaviour is introduced by this PR, so no new tests are warranted beyond the existing suite continuing to pass against the refactored code — which it does.

codescene-access[bot]

This comment was marked as outdated.

@leynos

leynos commented Jul 28, 2026

Copy link
Copy Markdown
Owner Author

@coderabbitai Have the following now been resolved?

  • In the pin-synchronisation helpers in test_maturin_build.py, pyproject.toml and the workflow/action YAML files are read multiple times within the same test run (e.g., _read_expected_maturin_version and _read_maturin_pins each re-open pyproject.toml), so consider caching these file contents per test module (e.g., via a small module-level cache or a fixture) to avoid redundant I/O and keep the helpers simpler.
  • In wheel_build_snapshot, the inline logic for locating the .dist-info/WHEEL entry and deriving the METADATA entry is now embedded directly in the function; if you intend to reuse this logic elsewhere, consider extracting a small internal helper (e.g., _dist_info_paths) to clarify the intent and make the error handling around missing WHEEL/METADATA entries easier to test and maintain.

@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

Tip

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '== Changed files =='
git diff --name-only origin/main...HEAD -- \
  cuprum/unittests/test_maturin_build.py \
  tests/helpers/maturin.py \
  docs/developers-guide.md

printf '%s\n' '== Test module outline =='
ast-grep outline cuprum/unittests/test_maturin_build.py --items all \
  --match 'maturin|pin|workflow|container' --view expanded || true

printf '%s\n' '== Helper module outline =='
ast-grep outline tests/helpers/maturin.py --items all \
  --match 'wheel|member|metadata|snapshot' --view expanded || true

printf '%s\n' '== Pin-reading helpers and calls =='
rg -n -A18 -B4 \
  'def _read_(expected_maturin_version|maturin_pins|manylinux_aarch64_container_ref)|def _workflow_uses_manylinux_aarch64_container_ref|read_text\(' \
  cuprum/unittests/test_maturin_build.py

printf '%s\n' '== Wheel member extraction and snapshot use =='
rg -n -A35 -B5 \
  'def _read_wheel_members|def wheel_build_snapshot|ZipFile|dist-info/WHEEL|METADATA' \
  tests/helpers/maturin.py

Length of output: 1413


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '%s\n' '== Test module: relevant declarations and uses =='
rg -n -A24 -B5 \
  '^(def _read_expected_maturin_version|def _read_maturin_pins|def _read_manylinux_aarch64_container_ref|def _workflow_uses_manylinux_aarch64_container_ref)|\b(_read_expected_maturin_version|_read_maturin_pins|_read_manylinux_aarch64_container_ref|_workflow_uses_manylinux_aarch64_container_ref)\(' \
  cuprum/unittests/test_maturin_build.py

printf '%s\n' '== Test module: every filesystem read =='
rg -n -C3 '\.read_text\(|open\(' cuprum/unittests/test_maturin_build.py || true

printf '%s\n' '== Helper module: wheel member extraction and caller =='
rg -n -A45 -B6 \
  '^(def _read_wheel_members|def wheel_build_snapshot)|ZipFile|dist-info/WHEEL|METADATA' \
  tests/helpers/maturin.py

Length of output: 13460


@leynos: Treat the two items separately:

  1. Pin-reading content cache — not resolved.
    _read_text() directly calls Path.read_text() (Line 59). The tests still reread pyproject.toml through _read_expected_maturin_version() (Line 65) and _read_maturin_pins() (Line 74), while build-wheels.yml is reread by both container helpers (Lines 96 and 105). Add a narrowly scoped cache or pass already-read content between the local helpers if eliminating that repeated I/O remains desired.

  2. Wheel member lookup extraction — resolved.
    tests/helpers/maturin.py now uses _read_wheel_members() (Lines 164–178) to locate .dist-info/WHEEL, derive/read METADATA, and report a missing WHEEL member. wheel_build_snapshot() delegates to it at Line 218, so this logic is no longer embedded inline.

Review round on the helper simplification:

- _read_wheel_members derived the METADATA member name and read it
  without checking membership, so a wheel missing that member raised
  KeyError from ZipFile.read rather than the AssertionError
  wheel_build_snapshot documents. Assert membership first, matching the
  existing WHEEL guard, and cover both missing-member cases with a
  parametrised test. Verified non-vacuous: removing the guard reproduces
  the KeyError the finding predicted.
- build_native_wheel_artifact runs `python -m maturin` under the current
  interpreter, so it uses whichever maturin that environment provides; it
  does not select a pinned version. Correct that claim in both the
  docstring and the developers guide, and name the two mechanisms that
  actually enforce alignment: the installed-CLI pin check and the
  snapshot test's Generator assertion.
- Add NumPy-style Returns sections to toolchain_available and
  wheel_build_snapshot, matching the Parameters/Raises sections already
  used in this module.
- Move docstring prose to Oxford -ize spelling per AGENTS.md. Identifiers
  keep the -ise spelling that prevails across the repository, since the
  rule governs comments rather than names.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
codescene-access[bot]

This comment was marked as outdated.

@codescene-access codescene-access 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.

No quality gates enabled for this code.

@pandalump

Copy link
Copy Markdown
Collaborator

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 29, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@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: 4

🤖 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 `@docs/developers-guide.md`:
- Around line 1403-1410: Update the regex ownership wording in the documentation
around the “shared regex” reference so it identifies the private test-local
regexes in test_maturin_build.py, consistent with the documented helpers and
regexes being inlined there. Do not describe them as shared.
- Around line 1417-1420: Update the documentation around
test_installed_maturin_matches_expected_pin to describe its actual check: it
verifies the installed maturin package version from current-interpreter metadata
via importlib.metadata.version("maturin"), while only gating on the CLI being
available on PATH; alternatively, change the implementation to obtain the
version with maturin --version.

In `@tests/helpers/maturin.py`:
- Around line 178-185: Reduce the _read_wheel_members docstring to a single-line
summary of its return value, removing the Raises section and its assertion
details while preserving any non-obvious guarantee needed by callers.
- Around line 81-84: Update the maturin availability check in the helper to
import the maturin module directly instead of calling importlib.util.find_spec,
and keep the ImportError fallback setting maturin_available to False. The check
must only report availability when the import succeeds.
🪄 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: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: b00727e6-01fd-4901-8543-64e2040a5c87

📥 Commits

Reviewing files that changed from the base of the PR and between 302858c and cc49f1f.

📒 Files selected for processing (3)
  • cuprum/unittests/test_maturin_build.py
  • docs/developers-guide.md
  • tests/helpers/maturin.py
🔗 Linked repositories identified

CodeRabbit considers these linked repositories for cross-repo context during reviews:

  • leynos/shared-actions (auto-detected)
  • leynos/pylint-pypy-shim (auto-detected)
  • leynos/whitaker (auto-detected)

Comment thread docs/developers-guide.md
Comment on lines +1403 to +1410
These checks live in `cuprum/unittests/test_maturin_build.py`, split across two
boundaries. The **pin-synchronization** checks are inlined there as private
helpers (`_read_maturin_pins`, `_read_expected_maturin_version`,
`_read_manylinux_aarch64_container_ref`, and their regexes): they read
repository files, have a single consumer, and gain nothing from indirection.
The **native wheel build and snapshot** machinery stays in
`tests/helpers/maturin.py`, because it wraps `subprocess` and `zipfile`
introspection that does not inline cleanly.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Correct the regex ownership description below.

Replace “shared regex” in Lines 1446-1450 with wording that identifies the
private test-local regexes; Lines 1403-1406 now explicitly document that the
helpers and regexes are inlined in test_maturin_build.py.

Triage: [type:docstyle]

🤖 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 `@docs/developers-guide.md` around lines 1403 - 1410, Update the regex
ownership wording in the documentation around the “shared regex” reference so it
identifies the private test-local regexes in test_maturin_build.py, consistent
with the documented helpers and regexes being inlined there. Do not describe
them as shared.

Source: Coding guidelines

Comment thread docs/developers-guide.md
Comment on lines +1417 to +1420
selecting a version itself. Two separate mechanisms enforce alignment with the
declared pin: `test_installed_maturin_matches_expected_pin` compares the
installed CLI against the `pyproject.toml` pin, and the snapshot test asserts
the built wheel's `Generator` matches that same pin, so a wheel built by an

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Describe the installed-version check accurately.

Replace “compares the installed CLI” with the current-interpreter package
metadata check, or invoke maturin --version. The test gates on a CLI being on
PATH but obtains the version through importlib.metadata.version("maturin").

Triage: [type:docstyle]

🤖 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 `@docs/developers-guide.md` around lines 1417 - 1420, Update the documentation
around test_installed_maturin_matches_expected_pin to describe its actual check:
it verifies the installed maturin package version from current-interpreter
metadata via importlib.metadata.version("maturin"), while only gating on the CLI
being available on PATH; alternatively, change the implementation to obtain the
version with maturin --version.

Comment thread tests/helpers/maturin.py
Comment on lines 81 to +84
try:
return importlib.util.find_spec("maturin") is not None
maturin_available = importlib.util.find_spec("maturin") is not None
except ImportError:
return False


def toolchain_available() -> bool:
"""Return whether the Rust toolchain and maturin are available."""
maturin_available = False

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
python - <<'PY'
import importlib.util

print(f"find_spec: {importlib.util.find_spec('maturin')!r}")
try:
    import maturin
except ImportError as exc:
    print(f"import failed: {exc!r}")
else:
    print("import succeeded")
PY

Repository: leynos/cuprum

Length of output: 231


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

file="tests/helpers/maturin.py"

python - <<'PY'
from pathlib import Path
path = Path("tests/helpers/maturin.py")
print(path.read_text())
PY

Repository: leynos/cuprum

Length of output: 10028


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

sed -n '1,180p' tests/helpers/maturin.py

Repository: leynos/cuprum

Length of output: 6514


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

nl -ba tests/helpers/maturin.py | sed -n '60,100p'
printf '\n---\n'
nl -ba tests/helpers/maturin.py | sed -n '170,200p'
printf '\n---\n'
rg -n "toolchain_available|find_spec\\(\"maturin\"|import maturin|python -m maturin|maturin" tests -n

Repository: leynos/cuprum

Length of output: 191


🌐 Web query:

Python importlib.util.find_spec does not import module broken installation spec importlib docs

💡 Result:

The function importlib.util.find_spec is designed to find the specification (ModuleSpec) for a module without actually performing a full import of that module [1][2][3]. However, it is important to be aware of a specific side effect: if you provide a dotted module name (a submodule), importlib.util.find_spec will automatically import the parent module [1][2][4][3]. Regarding your concern about broken installations or module resolution, here is how the behavior is handled: 1. Parent Module Import: Because find_spec performs this parent import to determine the correct path for a submodule, it will trigger the execution of the parent module's code (e.g., its init.py) [4][5][3]. If the parent module is broken or has a side effect on import, this will occur even though you are only attempting to "find" the spec of the child [3]. 2. Error Handling and Exceptions: If the module cannot be found, the function returns None [1][6]. However, depending on the Python version and the specific circumstances (such as a parent package lacking a path attribute or not existing), it may raise exceptions like ModuleNotFoundError or ValueError instead of returning None [4][7][8]. 3. Broken Installations: If you are encountering issues where find_spec returns an unexpected result (e.g., finding a module in a different directory) or fails, this often stems from how sys.path is configured or the presence of namespace packages that lack init.py files [9]. Since find_spec relies on the standard import machinery, it behaves exactly as the import statement would regarding path discovery [1][3]. If your goal is to verify existence without triggering any side effects from imports, you may need to inspect sys.path or use finders directly from sys.meta_path, rather than relying on the higher-level find_spec function, which inherently triggers the import of parent packages to resolve submodule locations [1][4][3].

Citations:


Import maturin here instead of using find_spec(). A spec can exist even when the module fails at import time, which would let this helper report the toolchain as available and push the failure to python -m maturin.

🤖 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/helpers/maturin.py` around lines 81 - 84, Update the maturin
availability check in the helper to import the maturin module directly instead
of calling importlib.util.find_spec, and keep the ImportError fallback setting
maturin_available to False. The check must only report availability when the
import succeeds.

Comment thread tests/helpers/maturin.py
Comment on lines +178 to 185
def _read_wheel_members(whl_path: Path) -> tuple[list[str], str, str]:
"""Return the entry names and the decoded ``WHEEL``/``METADATA`` payloads.

Raises
------
AssertionError
If no ``.dist-info/WHEEL`` entry is present.
If the archive is missing either ``.dist-info`` member.
"""

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Reduce this private helper docstring to one line.

Remove the redundant Raises section; the public
wheel_build_snapshot() docstring owns the caller-facing contract.

As per path instructions, “Use a single-line summary for private functions and
methods.” Based on learnings, private helper docstrings should retain only
non-obvious guarantees.

🤖 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/helpers/maturin.py` around lines 178 - 185, Reduce the
_read_wheel_members docstring to a single-line summary of its return value,
removing the Raises section and its assertion details while preserving any
non-obvious guarantee needed by callers.

Sources: Path instructions, Learnings

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

2 participants