Skip to content

refactor(language): group_sum becomes sum(group_by=) - #491

Merged
FBumann merged 4 commits into
mainfrom
refactor/sum-group-by
Aug 9, 2026
Merged

refactor(language): group_sum becomes sum(group_by=)#491
FBumann merged 4 commits into
mainfrom
refactor/sum-group-by

Conversation

@FBumann

@FBumann FBumann commented Aug 9, 2026

Copy link
Copy Markdown
Collaborator

One verb where there were two. sum reduces a dim away, or — given
group_by= — reduces it into the dim that coordinate targets.

sum(p, over=generator)                   # reduce the dim away
sum(p, over=generator, group_by=bus)     # reduce it into `bus`

Why group_by= and not by=

Folding the grouping into sum costs something real: the verb no longer
says a regrouping happened. group_sum announced it; sum(x, over=f, by=c)
would hide it in a keyword easy to skim past, and the result's dims change
either way.

group_by= puts it back where it is visible. sum(p, over=generator, group_by=bus) reads as what it is, and the cost of the rename is a keyword four
characters longer than it had to be.

The retirement is the migration story

No alias, no deprecation cycle — per breaking changes are free. So the old
spelling has to fail at load naming its rewrite, which is checked
(test_the_retired_group_sum_names_its_rewrite) in a way a shim would not be:

Constraint 'x': 'group_sum' is no longer a helper — the grouping moved into
`sum`, so one verb covers reducing a dim away and reducing it into another.
Write: sum(<expr>, over=<dim>, group_by=<coord>)

A habitual by= lands on the call-shape error, which quotes the usage line
including group_by.

Shape of the change

The surface collapses; the plan does not. Sum and GroupSum stay two
nodes, because reducing a dim away and reducing it into another are different
relational shapes and the executor cases were never what the surface was
conflating. What changed is one Builtin gaining an optional coordinate
kwarg, and the dim algebra and lowering branching on its presence.

One small generalisation fell out: Builtin gained
optional_coordinate_kwargs, since every existing coordinate kwarg was
mandatory.

A note on how this was done

The mechanical part was a corpus-wide rename over 42 files, and it collided
four times. Each was caught by a gate, and each is worth naming because a
blanket replace on an identifier that is a substring of its replacement is a
trap:

collision caught by effect if missed
_helper_group_sum_helper_sum an AST duplicate-def scan the second silently shadows the first, so plain sum calls the grouping helper
two tests named test_sum_over_typo_is_rejected ruff F811 one test stops running, silently
the RETIRED key 'group_sum''sum' a surface probe the retirement message never fires, and sum claims to be retired
tools/constructs.py column the generated-tables test the evidence page keeps a column named after a helper that no longer exists

The first and third are the ones that would have shipped quietly.

Scope and sequencing

This is a breaking surface change, and #432 exists to sequence those as one
window rather than piecemeal. Taken now deliberately; #332 and #432 get a note
so the remaining renames are decided against what actually landed rather than
against the old shape.

Branched from main, so it does not include at() (#489). The two touch the
same five files and whichever lands second rebases — at's own keyword question
(onto= vs over=) was settled in that PR for the same reason this one settles
group_by=: one keyword should not mean two directions.

806 passed, ruff / pyrefly / mkdocs --strict clean, goldens and generated
tables regenerated.

Summary by CodeRabbit

  • New Features
    • Grouped aggregation now uses sum(..., group_by=...).
    • Updated examples and models to reflect the new syntax.
    • Clear migration guidance is provided when the retired grouped-aggregation syntax is used.
  • Documentation
    • Updated specifications, guides, architecture references, benchmarks, and construct tables.
  • Bug Fixes
    • Improved validation and error messages for grouped dimensions and coordinates.
  • Tests
    • Updated and expanded coverage for grouped aggregation, validation, lowering, and rendering.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Aug 9, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@FBumann, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 11 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 9cac2b54-9e94-4567-b963-57654360aa1e

📥 Commits

Reviewing files that changed from the base of the PR and between 0916fec and 486f2ff.

⛔ Files ignored due to path filters (1)
  • examples/walkthrough.out is excluded by !**/*.out
📒 Files selected for processing (29)
  • bench/README.md
  • bench/cases.py
  • docs/ARCHITECTURE.md
  • docs/SPEC.md
  • docs/design/ceiling.md
  • docs/guide.md
  • docs/models/index.md
  • docs/models/monthly_budget.md
  • docs/models/multi_period.md
  • docs/models/pypsa_cyclic_storage.md
  • docs/models/pypsa_kvl.md
  • docs/models/pypsa_storage.md
  • docs/models/transport.md
  • docs/models/tsp_mtz.md
  • examples/README.md
  • src/lpspec/language/dimensions.py
  • src/lpspec/language/helpers.py
  • src/lpspec/language/resolution.py
  • src/lpspec/linopy/builder.py
  • src/lpspec/lowering.py
  • src/lpspec/relational/engines/polars/compiler.py
  • src/lpspec/relational/engines/polars/executor.py
  • src/lpspec/relational/plan.py
  • src/lpspec/typeset/walk.py
  • tests/test_arithmetic_laws.py
  • tests/test_at.py
  • tests/test_grouped_sum.py
  • tests/test_relational.py
  • tests/test_typeset.py
📝 Walkthrough

Walkthrough

This PR replaces group_sum(..., by=...) with sum(..., group_by=...). It updates helper registration, coordinate validation, lowering, execution, tests, examples, benchmarks, and documentation. Retired group_sum usage now reports replacement syntax.

Changes

Grouped sum migration

Layer / File(s) Summary
Helper contract and coordinate resolution
src/lpspec/language/*
sum now accepts optional group_by. Coordinate resolution supports optional coordinate arguments. Retired group_sum usage receives migration guidance.
Dimension validation and execution pipeline
src/lpspec/language/dimensions.py, src/lpspec/linopy/*, src/lpspec/lowering.py, src/lpspec/typeset/walk.py, src/lpspec/relational/engines/polars/*
Grouped aggregation uses sum(group_by=...) and lowers to either plan.Sum or plan.GroupSum. Related diagnostics and documentation use the new syntax.
Examples, models, and documentation
bench/*, docs/*, examples/*, tools/constructs.py
Benchmarks, model expressions, examples, specifications, guides, and construct listings replace group_sum with sum(..., group_by=...).
Validation and regression coverage
tests/*
Tests cover grouped lowering, dimension validation, invalid syntax, retired-helper errors, relational behavior, arithmetic behavior, and typeset naming.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related issues

Possibly related PRs

  • FBumann/lpspec#56 — Changes the helper definitions and handling related to sum and group_sum.
  • FBumann/lpspec#461 — Updates the same monthly budget model and syntax migration.
  • FBumann/lpspec#189 — Modifies grouped aggregation behavior and related tests in the relational backend.

Suggested labels: area:engine

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 62.26% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 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 identifies the main language refactor from group_sum to sum(group_by=) described in the changes.
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 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
⚔️ Resolve merge conflicts 💡
  • Resolve merge conflict in branch refactor/sum-group-by
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/sum-group-by

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@read-the-docs-community

read-the-docs-community Bot commented Aug 9, 2026

Copy link
Copy Markdown

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

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

🤖 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/design/ceiling.md`:
- Line 17: Remove the duplicate `sum` entry from the **Primitives** list,
keeping a single `sum` item that represents the operator with optional
`group_by` support.

In `@docs/models/monthly_budget.md`:
- Around line 207-209: Update the `sum` partition description in the monthly
budget documentation to qualify that only snapshots with non-null coordinates
belong to exactly one group; preserve the existing behavior that null-coordinate
terms are placed nowhere and contribute nothing.

In `@src/lpspec/relational/engines/polars/executor.py`:
- Line 531: Update the grouped-sum documentation to preserve the complete API
contract: in src/lpspec/relational/engines/polars/executor.py lines 531-531, use
sum(f, over=line, group_by=to) and sum(f, over=line, group_by=from); in
src/lpspec/relational/engines/polars/compiler.py lines 707-707, add over=line to
both network examples; and in src/lpspec/relational/engines/polars/compiler.py
lines 759-759, describe the operation as sum(..., over=..., group_by=...) or as
a grouped sum.

In `@tests/test_arithmetic_laws.py`:
- Around line 223-226: Update the explanatory comment near the mask test
description to remove the duplicated operator names and clearly distinguish the
two tested paths, using plain sum versus grouped sum with group_by or omitting
the parenthetical entirely.

In `@tests/test_group_sum.py`:
- Around line 101-104: Update the diagnostic regex assertions for the invalid
`group_by` cases in the test data to match `group_by=nope` and `group_by=to`
explicitly, rather than allowing the shorter `by=` suffix. Keep the existing
assertions for the `over` diagnostic and coordinate-scope behavior unchanged.

In `@tests/test_relational.py`:
- Line 652: Update the docstring of
test_two_sums_of_one_variable_collide_only_where_the_coordinates_meet to use the
current public syntax, replacing references to by=to and by=from with
group_by=to and group_by=from.
🪄 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: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: a5aab3c6-62ec-4966-bcc5-31ff780a0d5f

📥 Commits

Reviewing files that changed from the base of the PR and between 0066264 and 0916fec.

⛔ Files ignored due to path filters (1)
  • examples/walkthrough.out is excluded by !**/*.out
📒 Files selected for processing (46)
  • bench/README.md
  • bench/cases.py
  • bench/models/transport.yaml
  • docs/ARCHITECTURE.md
  • docs/SPEC.md
  • docs/design/ceiling.md
  • docs/guide.md
  • docs/models/index.md
  • docs/models/monthly_budget.md
  • docs/models/pypsa_cyclic_storage.md
  • docs/models/pypsa_kvl.md
  • docs/models/pypsa_ramp.md
  • docs/models/pypsa_storage.md
  • docs/models/pypsa_transport.md
  • docs/models/transport.md
  • docs/models/tsp_mtz.md
  • examples/README.md
  • examples/monthly_budget.yaml
  • examples/ports/pypsa_cyclic_storage.yaml
  • examples/ports/pypsa_kvl.yaml
  • examples/ports/pypsa_ramp.yaml
  • examples/ports/pypsa_storage.yaml
  • examples/ports/pypsa_transport.yaml
  • examples/ports/tsp_mtz.yaml
  • examples/transport.yaml
  • src/lpspec/language/dimensions.py
  • src/lpspec/language/expression_parser.py
  • src/lpspec/language/helpers.py
  • src/lpspec/language/resolution.py
  • src/lpspec/language/schema.py
  • src/lpspec/linopy/builder.py
  • src/lpspec/linopy/loader.py
  • src/lpspec/lowering.py
  • src/lpspec/relational/engines/polars/compiler.py
  • src/lpspec/relational/engines/polars/data_validation.py
  • src/lpspec/relational/engines/polars/executor.py
  • src/lpspec/typeset/walk.py
  • tests/golden/model.yaml
  • tests/test_arithmetic_laws.py
  • tests/test_compiler.py
  • tests/test_dimensions.py
  • tests/test_group_sum.py
  • tests/test_relational.py
  • tests/test_typeset.py
  • tests/test_validation.py
  • tools/constructs.py

Comment thread docs/design/ceiling.md Outdated
Comment thread docs/models/monthly_budget.md Outdated
Comment thread src/lpspec/relational/engines/polars/executor.py Outdated
Comment thread tests/test_arithmetic_laws.py Outdated
Comment thread tests/test_grouped_sum.py Outdated
Comment thread tests/test_relational.py
@codspeed-hq

codspeed-hq Bot commented Aug 9, 2026

Copy link
Copy Markdown

Merging this PR will improve performance by 29.78%

⚠️ Different runtime environments detected

Some benchmarks with significant performance changes were compared across different runtime environments,
which may affect the accuracy of the results.

Open the report in CodSpeed to investigate

⚡ 1 improved benchmark
✅ 13 untouched benchmarks
⏩ 10 skipped benchmarks1

Performance Changes

Benchmark BASE HEAD Efficiency
test_emit[sector-s-lpspec-lp] 8.7 MB 6.7 MB +29.78%

Tip

Curious why this is faster? Comment @codspeedbot explain why this is faster on this PR, or directly use the CodSpeed MCP with your agent.


Comparing refactor/sum-group-by (486f2ff) with main (0066264)

Open in CodSpeed

Footnotes

  1. 10 benchmarks were skipped, so the baseline results were used instead. If they were deleted from the codebase, click here and archive them to remove them from the performance reports.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@FBumann
FBumann merged commit fb14dd2 into main Aug 9, 2026
6 checks passed
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