Skip to content

Fix version bump with out-of-order TOML tables and workspace sections - #54

Merged
leynos merged 6 commits into
mainfrom
terragon/fix-version-bump-out-of-order-toml-f74owr
Dec 30, 2025
Merged

Fix version bump with out-of-order TOML tables and workspace sections#54
leynos merged 6 commits into
mainfrom
terragon/fix-version-bump-out-of-order-toml-f74owr

Conversation

@leynos

@leynos leynos commented Dec 29, 2025

Copy link
Copy Markdown
Owner

Summary

  • Fixes version bump handling when TOML contains out-of-order tables (OutOfOrderTableProxy) and updates workspace sections in manifest
  • Ensures bump logic works with non-standard TOML table ordering produced by tomlkit, including workspace dependencies

Changes

Core logic

  • Accept both Table and OutOfOrderTableProxy in _select_table, _update_dependency_table, and related helpers
  • Introduce _TableLike union/type alias to generalize table-like structures
  • Update type checks and assignments to support OutOfOrderTableProxy without breaking existing behavior
  • Ensure _assign_version can operate on out-of-order tables and still update the version field correctly
  • Add support for updating workspace dependency sections via a new _update_section helper and include_workspace_sections plumbing

Tests

  • Add test_select_table_handles_out_of_order_package to verify selecting a package table returns a valid table-like object when an OutOfOrderTableProxy is present
  • Add test_assign_version_works_with_out_of_order_table to verify version assignment works with OutOfOrderTableProxy
  • Add test_run_updates_workspace_dependency_sections to verify workspace dependency sections are updated (workspace.dependencies and other sections)

Test plan

  • Run unit tests for bump command internals and integration tests
  • Validate that a version bump updates the version field even when the TOML contains out-of-order tables
  • Validate workspace dependency sections updates for workspace sections (e.g., [workspace.dependencies])
  • Ensure no regressions for standard, well-ordered TOML structures

📎 Task: https://www.terragonlabs.com/task/5d8fd7af-a60e-4bda-a4fa-ee140503046d

When a Cargo.toml has [package.metadata.docs.rs] appearing after other
top-level tables like [dependencies], tomlkit returns an
OutOfOrderTableProxy instead of a Table. The _select_table function
previously only accepted Table instances, causing version bumps to be
silently skipped for such crates.

This change:
- Imports OutOfOrderTableProxy from tomlkit.container
- Adds _TableLike type alias (Table | OutOfOrderTableProxy)
- Updates _select_table to accept both table types
- Updates _assign_version and dependency functions accordingly
- Adds unit tests for out-of-order table handling

Closes #52

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@sourcery-ai

sourcery-ai Bot commented Dec 29, 2025

Copy link
Copy Markdown

Reviewer's Guide

Extend the bump command’s TOML handling to treat tomlkit OutOfOrderTableProxy objects as table-like in selection, dependency updating, and version assignment, and add regression tests for out-of-order [package] tables.

Class diagram for updated TOML table handling in bump command

classDiagram
    class Table
    class OutOfOrderTableProxy
    class TOMLDocument

    class _TableLike {
      <<interface>>
    }

    class BumpInternals {
      +_select_table(document: TOMLDocument | _TableLike, keys: tuple_str) _TableLike
      +_assign_version(table: _TableLike | None, target_version: str) bool
      +_update_dependency_table(table: _TableLike, dependency_names: Collection_str, target_version: str) bool
      +_update_dependency_entry(container: _TableLike, key: str, entry: object, target_version: str) bool
    }

    Table ..|> _TableLike
    OutOfOrderTableProxy ..|> _TableLike

    BumpInternals ..> Table
    BumpInternals ..> OutOfOrderTableProxy
    BumpInternals ..> TOMLDocument
    BumpInternals ..> _TableLike
Loading

File-Level Changes

Change Details Files
Generalize TOML table handling to support OutOfOrderTableProxy in bump logic.
  • Introduce a _TableLike alias and _TABLE_LIKE_TYPES tuple covering Table and OutOfOrderTableProxy.
  • Update _select_table to accept and return _TableLike objects and to use the generalized type tuple for isinstance checks.
  • Loosen the document parameter type of _select_table to accept _TableLike in addition to TOMLDocument.
lading/commands/bump.py
Allow dependency update helpers to work with table-like proxies without breaking typing.
  • Change _update_dependency_table and _update_dependency_entry to accept _TableLike containers.
  • Add targeted type: ignore[index] annotations where table-like objects are indexed or assigned to satisfy static type checkers while keeping behavior unchanged.
lading/commands/bump.py
Ensure version assignment works on out-of-order package tables and prevent regressions via tests.
  • Add test_select_table_handles_out_of_order_package to assert _select_table returns a usable table-like object when tomlkit produces an OutOfOrderTableProxy for [package].
  • Add test_assign_version_works_with_out_of_order_table to verify _assign_version updates the version field correctly on an OutOfOrderTableProxy-backed table.
tests/unit/test_bump_command_internals.py
lading/commands/bump.py

Possibly linked issues

  • #lading bump skips version when [package] is out-of-order: PR implements accepting OutOfOrderTableProxy in bump logic, exactly fixing the out-of-order [package] version skip bug.

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 Dec 29, 2025

Copy link
Copy Markdown

Summary by CodeRabbit

  • New Features

    • Added an option to update workspace-level dependency sections in Cargo.toml manifests.
    • Broadened manifest handling to support out-of-order TOML table structures for more reliable updates.
  • Tests

    • Added unit and integration tests covering workspace dependency updates and out-of-order TOML table scenarios.

✏️ Tip: You can customize this high-level summary in your review settings.

Walkthrough

Broaden TOML handling by introducing a _TableLike union (Table | OutOfOrderTableProxy), update multiple internal helpers and signatures to accept it, and add a BumpOptions flag to include workspace-level dependency sections.

Changes

Cohort / File(s) Summary
Core implementation
lading/commands/bump.py
Add `_TableLike = Table
Unit tests — internals
tests/unit/test_bump_command_internals.py
Add tests ensuring _select_table and _assign_version handle OutOfOrderTableProxy (out-of-order TOML tables) correctly.
Integration tests — workspace
tests/unit/test_bump_command_integration.py
Add parameterised test verifying workspace-level dependency sections (dependencies, dev-dependencies, build-dependencies) update correctly, covering both string and table/inline-table dependency forms.

Sequence Diagram(s)

(Skip; changes do not introduce a new multi-component control flow requiring a sequence diagram.)

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

Out-of-order snippets found their place,
_TableLike reached out, embraced the space,
Signatures widened, tests took the stage,
Workspace sections join the page —
TOML sings in tidy grace. 🎶

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately captures the main changes: fixing version bump handling for out-of-order TOML tables and adding workspace sections support.
Description check ✅ Passed The description comprehensively covers the PR objectives, including core logic changes, test additions, and validation approach, all directly related to the changeset.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch terragon/fix-version-bump-out-of-order-toml-f74owr

📜 Recent review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f4c6467 and 47e84b1.

📒 Files selected for processing (1)
  • tests/unit/test_bump_command_integration.py
🧰 Additional context used
📓 Path-based instructions (3)
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: For Python files, ensure changes pass all relevant unit and behavioral tests according to testing guidelines.
For Python files, ensure changes pass lint checks via make lint.
For Python files, ensure changes adhere to formatting standards via make check-fmt.
For Python files, ensure changes pass type checking via make typecheck.
For Python development, refer to detailed guidelines in the .rules/ directory including Python Code Style Guidelines, Context Managers, Exception Design/Raising/Handling/Logging, Generators, Project Configuration, Return Patterns, and Typing best practices.

**/*.py: Use snake_case.py for Python file names, naming them for their contents
Use PascalCase for class names
Use snake_case for variable and function names
Use UPPER_SNAKE_CASE for module-level constants
Prefix private or internal helpers with a single underscore (_)
Enable and maintain full static type coverage using Pyright; use typing everywhere
Use TypedDict or @DataClass(slots=True) for structured data
Avoid Any; use precise types (TypeVar, Protocol, Literal, Union) and typing.cast only when necessary with justification
Be explicit with return type annotations using -> None, -> str, etc., for all public functions and class methods
Prefer immutability: use tuples over lists and types.MappingProxyType for read-only mappings
Enforce strict mode in Pyright; treat all Pyright warnings as CI errors and use # pyright: ignore sparingly with explanation
Avoid side effects at import time; modules should not modify global state or perform actions on import
Document public functions, classes, and modules using NumPy-format docstrings
Use inline comments to explain tricky code and non-obvious logic

**/*.py: Use context managers (via contextlib.contextmanager or __enter__/__exit__ methods) to encapsulate setup and teardown logic for resource management (files, locks, connections, etc.)
Use @contextlib.contextmanager decorator for straightforward procedural setup...

Files:

  • tests/unit/test_bump_command_integration.py

⚙️ CodeRabbit configuration file

**/*.py: - Keep C90 / mccabe complexity ≤ 9

  • Follow single responsibility and CQRS (command/query segregation)
  • Prefer structural pattern matching to
  • Prefer structural pattern matching over isinstance() or imperative decomposition.
  • Docstrings must follow the numpy style guide. Use a single-line summary for private functions and methods, and full structured docs for all public interfaces.
  • Move conditionals with >2 branches to predicate/helper functions
  • Avoid eval, exec, pickle, monkey-patching, ctypes, unsafe shell
  • Every module must begin with a triple-quoted docstring explaining its purpose, utility, and usage, including example calls if appropriate.
  • Comments and docs must follow en-GB-oxendict (-ize / -yse / -our) spelling and grammar
  • Lint suppressions:
    • Blanket # noqa, file-level skips, and categories are forbidden
    • Only narrow in-line disables (# noqa: XYZ) are permitted, and must be accompanied by FIXME: or a ticket link, and used only as a last resort.
  • Use pytest fixtures for shared setup (conftest.py or fixtures/)
  • Replace duplicate tests with @pytest.mark.parametrize
  • Prefer pytest-mock or unittest.mock for stubs/mocks
  • Use assert …, "message" over bare asserts
  • Reflect all API/behaviour changes in docs/ and update roadmap on completion
  • Files must not exceed 400 logical lines:
    • Decompose large modules into subpackages
    • Split large match/case or dispatch tables by domain and collocate with targets if appropriate
    • Move bulky data (fixtures, templates) to external files for parsing at runtime
  • Mutable defaults and shadowed built-ins are forbidden
  • All code must have clear type hints using modern style (A | B, list[str], class Foo[A]:, type Bar = int, etc.), with ABC imports drawn from the correct stdlib module.
  • All path manipulation must be performed using pathlib for cross platform safety. Do not use string manipulation for extraction of path components or filename ele...

Files:

  • tests/unit/test_bump_command_integration.py
**/test_*.py

📄 CodeRabbit inference engine (.rules/python-00.md)

**/test_*.py: Use pytest idioms: prefer fixtures over setup/teardown, parametrize broadly, avoid unnecessary mocks
Group related tests using class with method names prefixed by test_
Write tests from a user's perspective; test public behavior, not internals
Avoid mocking too much; prefer test doubles only for external services or non-deterministic behaviors

Files:

  • tests/unit/test_bump_command_integration.py
**/*test*.py

📄 CodeRabbit inference engine (.rules/python-exception-design-raising-handling-and-logging.md)

In tests, use narrow exception assertions with pytest.raises() specifying the expected type and optionally constraining the message via regex (B017)

Files:

  • tests/unit/test_bump_command_integration.py
🧬 Code graph analysis (1)
tests/unit/test_bump_command_integration.py (5)
tests/unit/conftest.py (2)
  • _make_workspace (128-131)
  • _make_config (61-77)
tests/unit/test_cli.py (1)
  • _make_workspace (163-176)
tests/helpers/workspace_builders.py (2)
  • _make_workspace (100-106)
  • _make_config (123-135)
lading/cli.py (1)
  • bump (266-286)
lading/commands/bump.py (2)
  • run (115-133)
  • BumpOptions (55-64)
🔍 Remote MCP Deepwiki

Summary

Based on the comprehensive exploration of the PR context and supporting documentation, here is the relevant information for reviewing PR #54:

Key Problem Being Solved

The PR fixes version bump handling when TOML contains out-of-order tables (tomlkit.OutOfOrderTableProxy), which occurs when TOML sections appear in a non-standard order. The recent tomlkit library includes changes to "ensure unique table indices when adding items to out-of-order tables", making it essential for lading to handle these structures correctly.

Core Changes

The PR implements two main features:

  1. Out-of-Order Table Support: Introduces a _TableLike union type to accept both Table and OutOfOrderTableProxy, allowing version bump logic to work with non-sequentially ordered TOML tables. This requires creating a proxy to retrieve the proper objects from the parent container when an out-of-order table is encountered.

  2. Workspace Dependency Sections: Adds support for updating [workspace.dependencies], [workspace.dev-dependencies], and [workspace.build-dependencies] sections through a new include_workspace_sections parameter in BumpOptions.

Test Coverage

The PR adds three new tests:

  • Unit tests for _select_table() and _assign_version() with OutOfOrderTableProxy instances
  • Integration test test_run_updates_workspace_dependency_sections covering both string and table format dependencies

Note on Static Analysis Feedback: The CodeScene analysis flagged the test function with 5 parameters. As documented in the PR, removing the redundant expected_version parameter (which always equals target_version) reduces this to 4 parameters, satisfying the project's quality gate.

Architecture Context

The bump command uses tomlkit with format preservation, so keeping the nested out-of-order table structure is critical for maintaining comments and formatting during version updates. The command pipeline validates all modifications via atomic file writes to ensure crash-safety.

⏰ Context from checks skipped due to timeout of 120000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Sourcery review
🔇 Additional comments (3)
tests/unit/test_bump_command_integration.py (3)

10-10: LGTM!

The import of tk_items is necessary for the explicit type checking in the new test and follows proper import organization.


335-342: LGTM! Past review feedback addressed.

The isinstance check correctly distinguishes between table/inline-table formats and simple string formats using explicit type checking against tk_items.Table and tk_items.InlineTable. This addresses the previous review feedback to use explicit isinstance checks instead of hasattr(entry, "get").


310-333: The test is correctly written and does not require modification.

The run() function unconditionally calls _process_workspace_manifest() at line 124, which internally creates a modified BumpOptions instance with include_workspace_sections=True via dc.replace() at line 184. Workspace-level dependency sections are processed through this internal mechanism regardless of the include_workspace_sections value in the initial options passed to run(). The test will properly exercise workspace section updates as expected.


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

codescene-delta-analysis[bot]

This comment was marked as outdated.

@leynos
leynos marked this pull request as ready for review December 29, 2025 00:59

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

Hey - I've left some high level feedback:

  • Instead of sprinkling # type: ignore[index] around _TableLike usages, consider defining a small Protocol with __getitem__/__setitem__ and get so mypy/pyright understand the interface and you don’t need to suppress type checking at each call site.
  • _TABLE_LIKE_TYPES is currently untyped (typ.Final = (Table, OutOfOrderTableProxy)); giving it an explicit type such as typ.Final[tuple[type[Table], type[OutOfOrderTableProxy]]] would improve type safety and editor support when used in isinstance checks.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Instead of sprinkling `# type: ignore[index]` around `_TableLike` usages, consider defining a small `Protocol` with `__getitem__`/`__setitem__` and `get` so mypy/pyright understand the interface and you don’t need to suppress type checking at each call site.
- _TABLE_LIKE_TYPES is currently untyped (`typ.Final = (Table, OutOfOrderTableProxy)`); giving it an explicit type such as `typ.Final[tuple[type[Table], type[OutOfOrderTableProxy]]]` would improve type safety and editor support when used in `isinstance` checks.

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.

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

Caution

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

⚠️ Outside diff range comments (1)
lading/commands/bump.py (1)

447-460: Add justification for type: ignore comment on line 459.

Same rationale as above: the ignore directive needs explanation for maintainability.

🔎 Proposed fix
-    container[key] = replacement  # type: ignore[index]
+    container[key] = replacement  # type: ignore[index]  # OutOfOrderTableProxy supports item assignment
📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between df459be and 1bc2cba.

📒 Files selected for processing (2)
  • lading/commands/bump.py
  • tests/unit/test_bump_command_internals.py
🧰 Additional context used
📓 Path-based instructions (3)
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: For Python files, ensure changes pass all relevant unit and behavioral tests according to testing guidelines.
For Python files, ensure changes pass lint checks via make lint.
For Python files, ensure changes adhere to formatting standards via make check-fmt.
For Python files, ensure changes pass type checking via make typecheck.
For Python development, refer to detailed guidelines in the .rules/ directory including Python Code Style Guidelines, Context Managers, Exception Design/Raising/Handling/Logging, Generators, Project Configuration, Return Patterns, and Typing best practices.

**/*.py: Use snake_case.py for Python file names, naming them for their contents
Use PascalCase for class names
Use snake_case for variable and function names
Use UPPER_SNAKE_CASE for module-level constants
Prefix private or internal helpers with a single underscore (_)
Enable and maintain full static type coverage using Pyright; use typing everywhere
Use TypedDict or @DataClass(slots=True) for structured data
Avoid Any; use precise types (TypeVar, Protocol, Literal, Union) and typing.cast only when necessary with justification
Be explicit with return type annotations using -> None, -> str, etc., for all public functions and class methods
Prefer immutability: use tuples over lists and types.MappingProxyType for read-only mappings
Enforce strict mode in Pyright; treat all Pyright warnings as CI errors and use # pyright: ignore sparingly with explanation
Avoid side effects at import time; modules should not modify global state or perform actions on import
Document public functions, classes, and modules using NumPy-format docstrings
Use inline comments to explain tricky code and non-obvious logic

**/*.py: Use context managers (via contextlib.contextmanager or __enter__/__exit__ methods) to encapsulate setup and teardown logic for resource management (files, locks, connections, etc.)
Use @contextlib.contextmanager decorator for straightforward procedural setup...

Files:

  • tests/unit/test_bump_command_internals.py
  • lading/commands/bump.py

⚙️ CodeRabbit configuration file

**/*.py: - Keep C90 / mccabe complexity ≤ 9

  • Follow single responsibility and CQRS (command/query segregation)
  • Prefer structural pattern matching to
  • Prefer structural pattern matching over isinstance() or imperative decomposition.
  • Docstrings must follow the numpy style guide. Use a single-line summary for private functions and methods, and full structured docs for all public interfaces.
  • Move conditionals with >2 branches to predicate/helper functions
  • Avoid eval, exec, pickle, monkey-patching, ctypes, unsafe shell
  • Every module must begin with a triple-quoted docstring explaining its purpose, utility, and usage, including example calls if appropriate.
  • Comments and docs must follow en-GB-oxendict (-ize / -yse / -our) spelling and grammar
  • Lint suppressions:
    • Blanket # noqa, file-level skips, and categories are forbidden
    • Only narrow in-line disables (# noqa: XYZ) are permitted, and must be accompanied by FIXME: or a ticket link, and used only as a last resort.
  • Use pytest fixtures for shared setup (conftest.py or fixtures/)
  • Replace duplicate tests with @pytest.mark.parametrize
  • Prefer pytest-mock or unittest.mock for stubs/mocks
  • Use assert …, "message" over bare asserts
  • Reflect all API/behaviour changes in docs/ and update roadmap on completion
  • Files must not exceed 400 logical lines:
    • Decompose large modules into subpackages
    • Split large match/case or dispatch tables by domain and collocate with targets if appropriate
    • Move bulky data (fixtures, templates) to external files for parsing at runtime
  • Mutable defaults and shadowed built-ins are forbidden
  • All code must have clear type hints using modern style (A | B, list[str], class Foo[A]:, type Bar = int, etc.), with ABC imports drawn from the correct stdlib module.
  • All path manipulation must be performed using pathlib for cross platform safety. Do not use string manipulation for extraction of path components or filename ele...

Files:

  • tests/unit/test_bump_command_internals.py
  • lading/commands/bump.py
**/test_*.py

📄 CodeRabbit inference engine (.rules/python-00.md)

**/test_*.py: Use pytest idioms: prefer fixtures over setup/teardown, parametrize broadly, avoid unnecessary mocks
Group related tests using class with method names prefixed by test_
Write tests from a user's perspective; test public behavior, not internals
Avoid mocking too much; prefer test doubles only for external services or non-deterministic behaviors

Files:

  • tests/unit/test_bump_command_internals.py
**/*test*.py

📄 CodeRabbit inference engine (.rules/python-exception-design-raising-handling-and-logging.md)

In tests, use narrow exception assertions with pytest.raises() specifying the expected type and optionally constraining the message via regex (B017)

Files:

  • tests/unit/test_bump_command_internals.py
🧬 Code graph analysis (1)
tests/unit/test_bump_command_internals.py (1)
lading/commands/bump.py (2)
  • _select_table (691-707)
  • _assign_version (710-724)
🔍 Remote MCP Deepwiki

Based on my search through the repository and documentation, I've gathered comprehensive context about this PR. Let me provide a summary of the relevant findings for your pull request review:

Summary of Additional Context

What This PR Does

This pull request fixes version bump handling when tomlkit returns OutOfOrderTableProxy for out-of-order TOML tables. The fix is necessary because when TOML tables appear in non-standard order (e.g., [package], [dependencies], [package.metadata.docs.rs]), tomlkit returns a special proxy object instead of a regular Table, which caused the bump logic to fail when trying to update versions.

Key Technical Changes The PR introduces:

  1. New Type Union (_TableLike): A union type that accepts both Table and OutOfOrderTableProxy to generalize table-like structures across the bump command.

  2. Function Signature Updates: Core functions like _update_dependency_table, _update_dependency_entry, _select_table, and _assign_version now accept the broader _TableLike type instead of just Table.

  3. Type Check Expansion: The code now uses an isinstance() check against a _TABLE_LIKE_TYPES tuple containing both table types, ensuring nested table-like structures are handled consistently.

  4. New Import: OutOfOrderTableProxy is imported from tomlkit.container to support the type union.

Architectural Context The _select_table function is central to this fix. It navigates TOML documents to retrieve nested tables by key sequences. The PR updates the type checking logic so that both Table and OutOfOrderTableProxy instances are recognized as valid table-like objects during traversal.

Testing Coverage Two new unit tests verify the fix:

  • test_select_table_handles_out_of_order_package: Ensures selecting a package table returns a usable table-like object when an out-of-order [package.metadata.docs.rs] table appears after other sections
  • test_assign_version_works_with_out_of_order_table: Verifies version assignment works correctly with the proxy

Framework Context The project uses tomlkit specifically to preserve TOML formatting and comments during manifest rewrites. This is critical because the bump command must maintain user-defined document structure and formatting. The introduction of OutOfOrderTableProxy handling extends this formatting preservation to workspaces with non-standard TOML table ordering.

Related Architecture The bump command workflow involves:

  1. Parsing manifests with tomlkit to preserve structure
  2. Selecting appropriate tables for version updates
  3. Assigning new versions while preserving trivia (comments, whitespace)
  4. Writing changes atomically back to disk

The PR ensures all these steps work correctly when tables are out-of-order.

Code Quality Considerations for Review

Key areas to validate:

  • Type consistency: Verify that all code paths treating the union type handle both Table and OutOfOrderTableProxy identically in terms of indexing and attribute access
  • Test comprehensiveness: The two new tests should cover the most common out-of-order scenarios
  • Breaking changes: Confirm that the signature changes to internal helpers don't affect any external APIs or other modules
  • Type ignore markers: Review the necessity of any type: ignore comments added to suppress type checking warnings
⏰ Context from checks skipped due to timeout of 120000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Sourcery review
🔇 Additional comments (5)
tests/unit/test_bump_command_internals.py (2)

413-426: LGTM!

Test correctly verifies that _select_table handles OutOfOrderTableProxy when [package.metadata.docs.rs] appears after other sections, causing tomlkit to return a proxy object. The assertion chain is appropriate.


429-440: LGTM!

Test correctly verifies version assignment works with the proxy object. The assertions validate both the return value and the side effect on the table.

lading/commands/bump.py (3)

17-17: LGTM!

Import of OutOfOrderTableProxy from tomlkit.container is correctly placed with other tomlkit imports.


691-707: LGTM!

The _select_table function correctly handles both Table and OutOfOrderTableProxy via the _TABLE_LIKE_TYPES tuple. The isinstance checks properly narrow the type, and the return type annotation is accurate.


710-724: LGTM!

The _assign_version function signature correctly accepts _TableLike | None, enabling version updates on both Table and OutOfOrderTableProxy instances. The implementation logic remains sound.

Comment thread lading/commands/bump.py
Comment thread lading/commands/bump.py Outdated
Address PR review comments:
- Add explicit type annotation to _TABLE_LIKE_TYPES for improved type
  safety and editor support
- Add justification comments explaining why type: ignore[index] is
  needed (OutOfOrderTableProxy supports indexing/assignment at runtime
  but type stubs don't reflect this)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
codescene-delta-analysis[bot]

This comment was marked as outdated.

@leynos

leynos commented Dec 29, 2025

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Dec 29, 2025

Copy link
Copy Markdown
✅ Actions performed

Review triggered.

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.

leynos and others added 2 commits December 29, 2025 19:20
Move the workspace sections behavior flag into BumpOptions dataclass
where it belongs semantically alongside other flags like dry_run.

Changes:
- Add include_workspace_sections field to BumpOptions dataclass
- Update _update_manifest to check options.include_workspace_sections
- Add _update_workspace_dependency_sections helper function
- Update _process_workspace_manifest to set include_workspace_sections=True

This refactoring improves code organization by grouping related
behavioral flags together in the options object.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Reduce code duplication and nesting in dependency section handling:

- Add _update_section helper to consolidate table selection and update
- Merge _update_workspace_dependency_sections into _update_dependency_sections
  using include_workspace_sections parameter
- Reduce maximum nesting depth from 3 to 2

Add parametrized test for workspace dependency sections:

- Test [workspace.dependencies], [workspace.dev-dependencies], and
  [workspace.build-dependencies] sections
- Handle both simple string format and table format with version key
- Use clear test IDs for pytest output

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@leynos leynos changed the title Fix version bump when TOML tables are out-of-order Fix version bump with out-of-order TOML tables and workspace sections Dec 29, 2025
codescene-delta-analysis[bot]

This comment was marked as outdated.

@leynos

leynos commented Dec 29, 2025

Copy link
Copy Markdown
Owner Author

@coderabbitai Please suggest a fix for this issue and supply a prompt for an AI coding agent to enable it to apply the fix:

tests/unit/test_bump_command_integration.py

Comment on lines +309 to +339

def test_run_updates_workspace_dependency_sections(
    tmp_path: pathlib.Path,
    section_name: str,
    initial_version: str,
    target_version: str,
    expected_version: str,
) -> None:
    """Workspace-level dependency sections are updated with the new version."""
    workspace = _make_workspace(tmp_path)
    manifest_path = tmp_path / "Cargo.toml"
    manifest_path.write_text(
        "[workspace]\n"
        f'members = ["crates/alpha", "crates/beta"]\n\n'
        "[workspace.package]\n"
        'version = "0.1.0"\n\n'
        f"[workspace.{section_name}]\n"
        f"alpha = {initial_version}\n",
        encoding="utf-8",
    )
    configuration = _make_config()
    bump.run(
        tmp_path,
        target_version,
        options=bump.BumpOptions(configuration=configuration, workspace=workspace),
    )

    document = parse_toml(manifest_path.read_text(encoding="utf-8"))
    entry = document["workspace"][section_name]["alpha"]
    # Handle both simple string format and table format with version key
    version = entry["version"].value if hasattr(entry, "get") else entry.value
    assert version == expected_version

❌ New issue: Excess Number of Function Arguments
test_run_updates_workspace_dependency_sections has 5 arguments, max arguments = 4

@coderabbitai

coderabbitai Bot commented Dec 29, 2025

Copy link
Copy Markdown

Tip

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Read the test file to understand the parameterization context
cat tests/unit/test_bump_command_integration.py

Length of output: 11668


@leynos, the issue is that the test function has 5 parameters when the maximum allowed is 4. Examining the test cases, I noticed that expected_version is redundant—it always equals target_version in all three test scenarios.

Suggested Fix

Remove the expected_version parameter and use target_version directly in the assertion:

@pytest.mark.parametrize(
    ("section_name", "initial_version", "target_version"),
    [
        ("dependencies", '"0.1.0"', "1.2.3"),
        ("dev-dependencies", '{ version = "0.1.0" }', "2.0.0"),
        ("build-dependencies", '"0.1.0"', "3.0.0"),
    ],
    ids=["dependencies", "dev-dependencies", "build-dependencies"],
)
def test_run_updates_workspace_dependency_sections(
    tmp_path: pathlib.Path,
    section_name: str,
    initial_version: str,
    target_version: str,
) -> None:
    """Workspace-level dependency sections are updated with the new version."""
    workspace = _make_workspace(tmp_path)
    manifest_path = tmp_path / "Cargo.toml"
    manifest_path.write_text(
        "[workspace]\n"
        f'members = ["crates/alpha", "crates/beta"]\n\n'
        "[workspace.package]\n"
        'version = "0.1.0"\n\n'
        f"[workspace.{section_name}]\n"
        f"alpha = {initial_version}\n",
        encoding="utf-8",
    )
    configuration = _make_config()
    bump.run(
        tmp_path,
        target_version,
        options=bump.BumpOptions(configuration=configuration, workspace=workspace),
    )

    document = parse_toml(manifest_path.read_text(encoding="utf-8"))
    entry = document["workspace"][section_name]["alpha"]
    # Handle both simple string format and table format with version key
    version = entry["version"].value if hasattr(entry, "get") else entry.value
    assert version == target_version

AI Coding Agent Prompt

In the file `tests/unit/test_bump_command_integration.py`, refactor the test function `test_run_updates_workspace_dependency_sections` to reduce the parameter count from 5 to 4:

1. Locate the test function `test_run_updates_workspace_dependency_sections` and its `@pytest.mark.parametrize` decorator (around line 282).

2. In the `@pytest.mark.parametrize` decorator, remove `expected_version` from the parameter tuple and from all three test case tuples.

3. Remove the `expected_version: str` parameter from the function signature.

4. In the final assertion (last line of the function), change `assert version == expected_version` to `assert version == target_version`.

This refactoring eliminates a redundant parameter since `expected_version` always equals `target_version` in all test cases.

The expected_version parameter always equals target_version in all test
cases, making it redundant. This simplifies the test by reducing the
parameter count from 5 to 4.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
codescene-delta-analysis[bot]

This comment was marked as outdated.

@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

📜 Review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1bc2cba and f4c6467.

📒 Files selected for processing (2)
  • lading/commands/bump.py
  • tests/unit/test_bump_command_integration.py
🧰 Additional context used
📓 Path-based instructions (3)
**/*.py

📄 CodeRabbit inference engine (AGENTS.md)

**/*.py: For Python files, ensure changes pass all relevant unit and behavioral tests according to testing guidelines.
For Python files, ensure changes pass lint checks via make lint.
For Python files, ensure changes adhere to formatting standards via make check-fmt.
For Python files, ensure changes pass type checking via make typecheck.
For Python development, refer to detailed guidelines in the .rules/ directory including Python Code Style Guidelines, Context Managers, Exception Design/Raising/Handling/Logging, Generators, Project Configuration, Return Patterns, and Typing best practices.

**/*.py: Use snake_case.py for Python file names, naming them for their contents
Use PascalCase for class names
Use snake_case for variable and function names
Use UPPER_SNAKE_CASE for module-level constants
Prefix private or internal helpers with a single underscore (_)
Enable and maintain full static type coverage using Pyright; use typing everywhere
Use TypedDict or @DataClass(slots=True) for structured data
Avoid Any; use precise types (TypeVar, Protocol, Literal, Union) and typing.cast only when necessary with justification
Be explicit with return type annotations using -> None, -> str, etc., for all public functions and class methods
Prefer immutability: use tuples over lists and types.MappingProxyType for read-only mappings
Enforce strict mode in Pyright; treat all Pyright warnings as CI errors and use # pyright: ignore sparingly with explanation
Avoid side effects at import time; modules should not modify global state or perform actions on import
Document public functions, classes, and modules using NumPy-format docstrings
Use inline comments to explain tricky code and non-obvious logic

**/*.py: Use context managers (via contextlib.contextmanager or __enter__/__exit__ methods) to encapsulate setup and teardown logic for resource management (files, locks, connections, etc.)
Use @contextlib.contextmanager decorator for straightforward procedural setup...

Files:

  • tests/unit/test_bump_command_integration.py
  • lading/commands/bump.py

⚙️ CodeRabbit configuration file

**/*.py: - Keep C90 / mccabe complexity ≤ 9

  • Follow single responsibility and CQRS (command/query segregation)
  • Prefer structural pattern matching to
  • Prefer structural pattern matching over isinstance() or imperative decomposition.
  • Docstrings must follow the numpy style guide. Use a single-line summary for private functions and methods, and full structured docs for all public interfaces.
  • Move conditionals with >2 branches to predicate/helper functions
  • Avoid eval, exec, pickle, monkey-patching, ctypes, unsafe shell
  • Every module must begin with a triple-quoted docstring explaining its purpose, utility, and usage, including example calls if appropriate.
  • Comments and docs must follow en-GB-oxendict (-ize / -yse / -our) spelling and grammar
  • Lint suppressions:
    • Blanket # noqa, file-level skips, and categories are forbidden
    • Only narrow in-line disables (# noqa: XYZ) are permitted, and must be accompanied by FIXME: or a ticket link, and used only as a last resort.
  • Use pytest fixtures for shared setup (conftest.py or fixtures/)
  • Replace duplicate tests with @pytest.mark.parametrize
  • Prefer pytest-mock or unittest.mock for stubs/mocks
  • Use assert …, "message" over bare asserts
  • Reflect all API/behaviour changes in docs/ and update roadmap on completion
  • Files must not exceed 400 logical lines:
    • Decompose large modules into subpackages
    • Split large match/case or dispatch tables by domain and collocate with targets if appropriate
    • Move bulky data (fixtures, templates) to external files for parsing at runtime
  • Mutable defaults and shadowed built-ins are forbidden
  • All code must have clear type hints using modern style (A | B, list[str], class Foo[A]:, type Bar = int, etc.), with ABC imports drawn from the correct stdlib module.
  • All path manipulation must be performed using pathlib for cross platform safety. Do not use string manipulation for extraction of path components or filename ele...

Files:

  • tests/unit/test_bump_command_integration.py
  • lading/commands/bump.py
**/test_*.py

📄 CodeRabbit inference engine (.rules/python-00.md)

**/test_*.py: Use pytest idioms: prefer fixtures over setup/teardown, parametrize broadly, avoid unnecessary mocks
Group related tests using class with method names prefixed by test_
Write tests from a user's perspective; test public behavior, not internals
Avoid mocking too much; prefer test doubles only for external services or non-deterministic behaviors

Files:

  • tests/unit/test_bump_command_integration.py
**/*test*.py

📄 CodeRabbit inference engine (.rules/python-exception-design-raising-handling-and-logging.md)

In tests, use narrow exception assertions with pytest.raises() specifying the expected type and optionally constraining the message via regex (B017)

Files:

  • tests/unit/test_bump_command_integration.py
🧬 Code graph analysis (1)
tests/unit/test_bump_command_integration.py (5)
tests/unit/conftest.py (1)
  • _make_workspace (128-131)
tests/unit/test_cli.py (1)
  • _make_workspace (163-176)
tests/helpers/workspace_builders.py (1)
  • _make_workspace (100-106)
lading/cli.py (1)
  • bump (266-286)
lading/commands/bump.py (2)
  • run (115-133)
  • BumpOptions (55-64)
⏰ Context from checks skipped due to timeout of 120000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Sourcery review
  • GitHub Check: Sourcery review
🔇 Additional comments (10)
lading/commands/bump.py (10)

17-17: LGTM!

Import correctly added for OutOfOrderTableProxy to support the new _TableLike union.


33-38: LGTM!

Type alias and constant are well-defined with explicit annotations. The use of PEP 695 type keyword and typ.Final for the tuple aligns with the coding guidelines.


64-64: LGTM!

New include_workspace_sections field with a sensible default maintains backward compatibility.


181-185: LGTM!

Correctly enables include_workspace_sections specifically for the workspace manifest via immutable dc.replace.


366-382: LGTM!

Docstring clearly documents the include_workspace_sections behaviour, and the option is correctly propagated to _update_dependency_sections.


426-447: LGTM!

Clean refactor with the new _update_section helper. The conditional workspace section handling is clear and maintains backward compatibility via the default value.


450-464: LGTM!

Well-extracted helper with single responsibility. The docstring clearly explains the path tuple convention.


467-496: LGTM!

Type signatures correctly updated to _TableLike. The type: ignore comments now include justifications explaining OutOfOrderTableProxy runtime behaviour, as required by coding guidelines.


727-743: LGTM!

The _select_table function correctly handles both Table and OutOfOrderTableProxy using consistent isinstance checks against _TABLE_LIKE_TYPES. The logic properly returns None when navigation fails or when an empty keys tuple is passed with a non-table-like document.


746-760: LGTM!

Type signature correctly broadened to _TableLike | None, enabling version assignment on OutOfOrderTableProxy instances without any logic changes.

Comment thread tests/unit/test_bump_command_integration.py
The expected_version parameter always equals target_version in all test
cases, making it redundant. This simplifies the test by reducing the
parameter count from 5 to 4.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>

@codescene-delta-analysis codescene-delta-analysis 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.

Gates Passed
6 Quality Gates Passed

See analysis details in CodeScene

Absence of Expected Change Pattern

  • lading/lading/commands/bump.py is usually changed with: lading/tests/unit/test_cli.py

Quality Gate Profile: Pay Down Tech Debt
Want more control? Customize Code Health rules or catch issues early with our IDE extension and CLI tool.

@leynos
leynos merged commit bc8aaf1 into main Dec 30, 2025
4 checks passed
@leynos
leynos deleted the terragon/fix-version-bump-out-of-order-toml-f74owr branch December 30, 2025 00:37
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