Skip to content

Annotate return types of GF and IntegerModRing factories - #42670

Merged
vbraun merged 8 commits into
sagemath:developfrom
starnotes-xj:annotate-ring-factory-return-types
Aug 23, 2026
Merged

vbraun merged 8 commits into
sagemath:developfrom
starnotes-xj:annotate-ring-factory-return-types

Conversation

@starnotes-xj

Copy link
Copy Markdown
Contributor

Static type checkers (Pyright, mypy, PyCharm) cannot infer the return type
of GF, Zmod, Integers and IntegerModRing because these are instances
of UniqueFactory subclasses whose Cython __call__ carries no
annotation. Downstream tooling currently compensates by probing the factory
at runtime (e.g. the
sage-pycharm-stubgen
engine infers and ships these types for the IDE); annotating the factories
upstream makes the same information available to every tool.

This PR adds an annotated, purely forwarding __call__ override to the two
factory classes:

  • FiniteFieldFactory.__call__ returns FiniteField (the common importable
    base of FiniteField_prime_modn, FiniteField_givaro,
    FiniteField_ntl_gf2e, FiniteField_pari_ffelt);
  • IntegerModFactory.__call__ returns
    IntegerModRing_generic | IntegerRing_class, because Integers(0) returns
    ZZ.

Both signatures were verified against Sage 10.9 at runtime:
inspect.signature now reports the annotations, import sage.all is
unaffected (no import cycles), the doctests of both modules pass, and the
factory behavior is unchanged for GF(29), GF(2^8, 'a'), Zmod(17) and
Integers(0).

The remaining ring factories from the runtime probe (58 in total, e.g.
RealField, ComplexField, NumberField, ...) can be annotated in
follow-up PRs.

🤖 Generated with Claude Code

Copilot AI lite review requested due to automatic review settings August 16, 2026 06:01

Copilot AI 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.

Pull request overview

This PR aims to improve static typing support for Sage’s finite field and integer-mod-ring factory constructors by adding explicit return type annotations to the UniqueFactory subclasses behind GF/FiniteField and Zmod/Integers/IntegerModRing.

Changes:

  • Add a forwarding, annotated __call__ override to FiniteFieldFactory so type checkers can infer GF(...) -> FiniteField.
  • Add a forwarding, annotated __call__ override to IntegerModFactory so type checkers can infer Integers(n) -> IntegerModRing_generic | ZZ.
  • Import FiniteField from finite_field_base for the new annotation.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
src/sage/rings/finite_rings/integer_mod_ring.py Adds an annotated IntegerModFactory.__call__ to expose the factory’s return type.
src/sage/rings/finite_rings/finite_field_constructor.py Imports FiniteField and adds an annotated FiniteFieldFactory.__call__ to expose the factory’s return type.
Suppressed comments (1)

src/sage/rings/finite_rings/finite_field_constructor.py:202

  • This forwarding Python-level __call__ adds an extra Python frame to every GF(...)/FiniteField(...) invocation compared to dispatching directly to UniqueFactory.__call__. Since GF is a very hot constructor and often hits the cache, this can be a measurable regression.
class FiniteFieldFactory(UniqueFactory):
    def __call__(self, *args, **kwds) -> FiniteField:
        return super().__call__(*args, **kwds)


💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@starnotes-xj starnotes-xj mentioned this pull request Aug 16, 2026
5 tasks
Static type checkers cannot infer the return type of GF, Zmod,
Integers and IntegerModRing because these are UniqueFactory instances
whose Cython __call__ carries no annotation.  Add an annotated,
purely forwarding __call__ override to the two factory classes:

- FiniteFieldFactory.__call__ returns FiniteField, the common base of
  FiniteField_prime_modn, FiniteField_givaro, FiniteField_ntl_gf2e and
  FiniteField_pari_ffelt;
- IntegerModFactory.__call__ returns IntegerModRing_generic or
  IntegerRing_class, because Integers(0) returns ZZ.

Verified against Sage 10.9: the annotations appear in
inspect.signature, import sage.all is unaffected, the doctests of both
modules pass, and factory behavior is unchanged for GF(29),
GF(2^8, 'a'), Zmod(17) and Integers(0).
@starnotes-xj
starnotes-xj force-pushed the annotate-ring-factory-return-types branch from daea1f3 to 6bbcfc4 Compare August 16, 2026 07:40
@starnotes-xj

Copy link
Copy Markdown
Contributor Author

@cxzhong thanks again for the review — the fix has been pushed: __call__ now sits after the class docstring in both src/sage/rings/finite_rings/integer_mod_ring.py and src/sage/rings/finite_rings/finite_field_constructor.py, so the factory class docstrings are preserved. The branch is updated to 6bbcfc4, ready for another look.

@tobiasdiez tobiasdiez 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.

Thanks, looks good to me.

Maybe add a comment explaining that this method is there only for the typing info.

@sagemath/core could you please run the CI.

@cxzhong

cxzhong commented Aug 16, 2026

Copy link
Copy Markdown
Contributor

Thanks — moving both overrides below the class docstrings fixes the original issue in both factories: the class docstrings are again the first class-body statements, so class-level documentation and introspection are preserved.

I also checked the return types. Every FiniteFieldFactory.create_object branch returns a subclass of finite_field_base.FiniteField, while IntegerModFactory.create_object returns IntegerRing_class for order zero and IntegerModRing_generic otherwise. The forwarding override adds one small, constant Python-frame overhead, but still dispatches directly to UniqueFactory.__call__; I do not see a meaningful behavioral or practical performance regression.

One compatibility fix remains: please import the finite-field base under a stable alias, for example:

from sage.rings.finite_rings.finite_field_base import FiniteField as FiniteField_base

and use -> FiniteField_base. The module later executes:

GF = FiniteField = FiniteFieldFactory(...)

With Python 3.14’s deferred annotation evaluation, the current annotation can therefore resolve to the factory instance when first inspected rather than to the base class. The alias also avoids the same-name type/value rebinding for mypy. With that rename, this looks good to me.

Add a comment explaining that the __call__ overrides exist only to
expose the return types to static type checkers (review feedback).
The TESTS blocks assert, on every backend, that the annotated return
type matches the runtime type:

- typing.get_type_hints(type(GF).__call__)['return'] is FiniteField
- GF(2^8, 'a', implementation=impl) is a FiniteField for givaro/ntl/pari_ffelt
- typing.get_type_hints(type(Zmod).__call__)['return'] equals the declared union
- Zmod(29) is an IntegerModRing_generic; Integers(0) is an IntegerRing_class

This mechanically guards the annotations against future runtime drift
(replacing the manual verification against Sage 10.9).
@starnotes-xj

Copy link
Copy Markdown
Contributor Author

I've prepared three additions around this PR's typing work, based on
runtime evidence collected against Sage 10.9:

1. Regression doctests for this PR (pushed here in a10665b)

The __call__ overrides now carry TESTS blocks that mechanically assert
the annotation matches the runtime type — replacing the manual verification:

  • typing.get_type_hints(type(GF).__call__)['return'] is FiniteField
  • GF(2**8, 'a', implementation=impl) is a FiniteField for givaro /
    ntl / pari_ffelt, plus GF(29)
  • the declared union for Zmod equals IntegerModRing_generic | IntegerRing_class, with Zmod(29) and Integers(0) instance checks

This guards the annotations against runtime drift in future releases.

2. Follow-up draft PR #42672: element-returning methods

The factory annotation gives checkers the field type, but the chain still
breaks on the next step — F.gen(), F.from_integer(0x57),
F.random_element(), F.multiplicative_generator() are unannotated.
The runtime probe across all three backends shows their common base is
FinitePolyExtElement (sage.rings.finite_rings.element_base):

backend element class
givaro FiniteField_givaroElement
ntl FiniteField_ntl_gf2eElement
pari_ffelt FiniteFieldElement_pari_ffelt

Draft: #42672 (annotations only, no
behavior change; Cython 3 keeps them on cdef-class methods, as _latex_
already does in the same file).

3. Downstream convergence in sage-pycharm-stubgen

Once this PR merges, the stub engine prefers the source-declared return
annotation over its runtime probing, and the probe becomes a fallback for
older Sage installations:
https://github.com/starnotes-xj/sage-pycharm-stubgen (commit
infer_factory_returns prefers typing.get_type_hints, 3/3 new tests).

Happy to adjust anything here (including dropping the doctests if you
prefer keeping the overrides minimal).

@starnotes-xj

Copy link
Copy Markdown
Contributor Author

One more offer alongside the three posted earlier — a type-stub
regression gate for this work (no change needed to this PR).

The external stub engine (sage-pycharm-stubgen, PyPI) has a strict
audit mode that fails when a detected factory loses its importable static
return type or when a sage.all export falls back to Any. A run
against Sage 10.9 generates 576 stubs, infers 60 factory return types and
reports 0 unresolved — the same runtime probing that produced the
annotation table in the PR description.

Suggestion: once these annotations land, add an optional/nightly CI lane
(or a developer-facing tox/make target) that installs the engine
(pip install sage-pycharm-stubgen) and runs sage-pycharm-stubgen --strict against the built tree. That would turn the factory return
types into a continuously-verified contract: any upstream change that
breaks static resolvability (dynamic class renames, factory behavior
changes) fails the check before a release instead of surfacing as
regressions in downstream tooling.

The engine intentionally supports older Sage versions (runtime probing
falls back when the source annotations of #42670 are absent), so the same
CI lane also works on the supported release branches.

Happy to prepare a follow-up PR adding the lane if there is interest.

The typing.get_type_hints(...) is FiniteField identity check failed on
the Python 3.14 CI job (sage's 3.14 build resolves the annotation to a
non-identical object).  The isinstance assertions are the actual
regression guard for the annotation contract; keep those and drop the
fragile get_type_hints comparisons.
@starnotes-xj

Copy link
Copy Markdown
Contributor Author

@cxzhong the Python 3.14 CI failure is fixed — thanks for running the tests.

What happened: one of the TESTS doctests asserted
typing.get_type_hints(type(GF).__call__)['return'] is FiniteField, which
failed on the Python 3.14 job (the annotation resolves to a non-identical
object in that build).

The fix (pushed as bea9305): dropped the fragile get_type_hints
identity/equality assertions from both TESTS blocks and kept the
isinstance checks — those are the actual regression guard for the
annotation contract (every backend's runtime type must remain a
FiniteField / IntegerModRing_generic / IntegerRing_class).

@sagemath/core could you please approve and re-run the CI on the updated
head (bea9305)? The new runs are waiting in the action_required
state.

@starnotes-xj

Copy link
Copy Markdown
Contributor Author

Status update on the CI runs (run 31956724841 and siblings):

  1. All three red jobs were executed on the pre-fix head a10665b. Each failed with exactly one doctest — the typing.get_type_hints(type(GF).__call__)['return'] is FiniteField identity check — and nothing else. The follow-up bea9305 removes that fragile comparison from both files (the isinstance assertions, which passed on every Python-version/backend combination including 3.14, remain as the actual contract guard). I re-verified those isinstance assertions locally against Sage 10.9: all pass.
  2. Unrelated flake: the non-meson "Build & Test" run additionally shows src/sage/libs/ecl.pyx # Killed due to abort in the [g-o] shard — the ECL sigint doctest aborting against the system libecl 24.5 on Python 3.14. This PR only touches finite_field_constructor.py and integer_mod_ring.py, so that crash is not related to these changes; it may need a shard re-run.
  3. The workflow runs generated for the current head bea9305 are sitting in action_required. Could a maintainer approve them so we get a clean green run? Thanks!

@starnotes-xj

Copy link
Copy Markdown
Contributor Author

Thanks for the approvals! One clarification on the CI state, plus the verification evidence:

Current state: the code is approved (tobiasdiez, cxzhong), but the workflow runs created for the current head bea9305 are still sitting in action_required — they have not been approved to execute, so no CI has ever run on the fixed head. The red checks visible on this PR are all from the pre-fix head a10665b.

Which of those red runs were caused by this PR, and which were not:

  1. Python 3.14 doctest failure (typing.get_type_hints(type(GF).__call__)['return'] is FiniteField) — was ours; fixed by bea9305, which drops the identity comparison and keeps the isinstance assertions.
  2. src/sage/libs/ecl.pyx # Killed due to abort in the docker "Build & Test" job — not caused by this PR. It is sage's own ECL sigint doctest aborting against the system libecl 24.5 on Python 3.14, and it reproduces on the same bea9305 head in my fork's CI (starnotes-xj/sage), where this PR's only touched files are the two ring modules. That shard would need a re-run regardless of this PR.

Fork-CI verification of bea9305 (identical pull_request workflows, same head, no approval gate — starnotes-xj#1):

workflow result
Build & Test using Meson (3.12 / 3.13 / 3.14 × ubuntu / macos / windows) green
Build & Test with all meson features disabled green
Lint green
Static type check green
Build documentation (PDF) green
Build documentation (html) fails only because the fork has no develop baseline artifact to download ("Download old doc" → Not Found) — a fork-infrastructure gap, not a code issue
Build & Test (docker) fails only with the ecl.pyx abort above

So the current head is green on every check that can run in a fork. Could a maintainer approve the pending action_required workflow runs on bea9305 so the checks show green here as well? Thanks!

@starnotes-xj

Copy link
Copy Markdown
Contributor Author

Note: the remaining docker-CI redness (ecl.pyx # Killed due to abort on 3.14) is tracked upstream now — see issue #42680. It reproduces on branches that do not touch libs/ecl.pyx at all, so it is independent of this PR.

@vincentmacri vincentmacri left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggestion to avoid the extra function calls.

Comment on lines +507 to +524
# This override is only there for the typing info: it exists so that
# static type checkers can infer the return type of ``GF``. The
# behavior is identical to the ``UniqueFactory`` base implementation.
def __call__(self, *args, **kwds) -> FiniteField:
"""
TESTS:

The return annotation matches the runtime type for every backend::

sage: from sage.rings.finite_rings.finite_field_base import FiniteField
sage: all(isinstance(GF(2**8, 'a', implementation=impl), FiniteField)
....: for impl in ('givaro', 'ntl', 'pari_ffelt'))
True
sage: isinstance(GF(29), FiniteField)
True
"""
return super().__call__(*args, **kwds)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
# This override is only there for the typing info: it exists so that
# static type checkers can infer the return type of ``GF``. The
# behavior is identical to the ``UniqueFactory`` base implementation.
def __call__(self, *args, **kwds) -> FiniteField:
"""
TESTS:
The return annotation matches the runtime type for every backend::
sage: from sage.rings.finite_rings.finite_field_base import FiniteField
sage: all(isinstance(GF(2**8, 'a', implementation=impl), FiniteField)
....: for impl in ('givaro', 'ntl', 'pari_ffelt'))
True
sage: isinstance(GF(29), FiniteField)
True
"""
return super().__call__(*args, **kwds)
__call__: Callable[..., FiniteField] # So static type checkers can infer the return type of ``GF``.

I think this works without having to potentially introduce more function call overhead? If this works, can you make the same change in the other file? You'll probably need to move the tests somewhere else (maybe the TESTS block of the class).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Using generics would be another option, but I think that would likely be a much larger change than we want to deal with right now.

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.

Agreed. Increasing the number of function calls just to aid type inference is a bad deal: function calls incur a real, expensive penalty, as does the "super" lookup. It's not clear type inference in python has a real benefit. The python interpreter is certainly declared-type-agnostic.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I think type inference has a real benefit for development and LSP projects (which have the potential to make writing Sage code easier for users), but I agree that we ought to find a way to do it without a performance penalty. While I can't measure a slowdown in this particular case, that's likely just because the slowdown is insignificant compared to the rest of the overhead of calling GF, but if we were to optimize the GF factory then this slowdown might start to be more apparent.

With the current state of the CPython interpreter, you are correct that there is no real runtime benefit (although I think some CPython devs have mused about potentially incorporating type hint information into a JIT compiler one day, we are a long way out from that being real).

Replace the forwarding __call__ overrides with bare class-level
variable annotations: static type checkers still infer the factory
return types, while factory calls keep dispatching directly to the
inherited UniqueFactory.__call__ with no extra Python frame or
super() lookup (review feedback).  Move the regression doctests to
class-level TESTS blocks and add a structural check that the
__call__ annotation resolves to the declared return type.

Import FiniteField under the alias FiniteField_base so that the
annotation resolves to the class rather than to the factory instance
once PEP 649 deferred annotations (Python 3.14) evaluate it through
the live module namespace.
@starnotes-xj

Copy link
Copy Markdown
Contributor Author

@vincentmacri @nbruin thanks — I've implemented exactly the inline suggestion: the forwarding __call__ overrides are gone, replaced by bare class-level annotations (pushed as c5bdfdf):

# finite_field_constructor.py
__call__: Callable[..., FiniteField_base]

# integer_mod_ring.py
__call__: Callable[..., "IntegerModRing_generic | integer_ring.IntegerRing_class"]

No runtime penalty anymore. The annotation assigns no value, so type(GF).__call__ is still the inherited UniqueFactory.__call__ — no extra Python frame and no super() lookup per factory call; the only cost is one entry in __annotations__ at class creation. This addresses @nbruin's point directly: paying per-call overhead for typing info would indeed be a bad deal.

Tests moved to class-level TESTS blocks as suggested. They now also assert structurally that the annotation resolves to the declared return type (== comparisons only, no is — safe under 3.14's deferred annotations).

@cxzhong's alias request is also in: FiniteField is now imported as FiniteField_base. This matters under PEP 649 (Python 3.14), where the annotation is evaluated lazily through the live module namespace: after GF = FiniteField = FiniteFieldFactory(...) the bare name would resolve to the factory instance, not the class. I reproduced that on CPython 3.14.4 — with the alias the annotation resolves to the class. (The Zmod annotation was already a forward reference, so it was safe.)

Why we want this typing info at all — agreed that it is for the static-tooling layer, not the interpreter (which ignores declared types). It is the input contract of two downstream projects:

  • sage-pycharm-stubgen (PyPI) generates the .pyi stubs for Sage and since v0.8 prefers source-declared annotations (typing.get_type_hints) over runtime probing. This PR makes the GF/Zmod return types source-declared, so the published stubs carry GF(...) -> FiniteField as a stable contract instead of relying on the probe.
  • The JetBrains IDE plugin consumes those stubs: in PyCharm, F = GF(2**8, 'a') then F. completes with typed methods, and the chain continues (F.from_integer(...) → element type → e. completions). Without the declared return type the whole chain degrades to Any and completion disappears.
  • The platform-side companion is JetBrains/intellij-community#3614, same goal.

Verification: mypy and pyright — including 1.1.332, the exact version pinned in sage's types.yml CI lane, and current 1.1.411 — all infer GF(2**8, 'a') → FiniteField and Zmod(29) → IntegerModRing_generic | IntegerRing_class from the bare annotations; the new TESTS bodies pass against an installed Sage 10.9 with these two files overlaid; ruff with the CI config passes in both --no-preview and --preview modes.

The push regenerated the workflow runs, so they will need maintainer approval again to execute. Happy to adjust anything else.

# would add a Python frame and a ``super()`` lookup to every factory
# call. No value is assigned, so instances keep dispatching directly
# to the inherited ``UniqueFactory.__call__`` at full speed.
__call__: Callable[..., "IntegerModRing_generic | integer_ring.IntegerRing_class"]

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Suggested change
__call__: Callable[..., "IntegerModRing_generic | integer_ring.IntegerRing_class"]
__call__: Callable[..., IntegerModRing_generic | integer_ring.IntegerRing_class]

I think some combination of from __future__ import annotations and placing some imports in an if TYPE_CHECKING block should allow you to remove these quotes, which I think helps with readability (I'm actually surprised the linter allowed this through, I thought UP037 enforced this). If there is something weird about Callable and you can't get it working without the string, no worries.

@vincentmacri

Copy link
Copy Markdown
Member

One more small request (although perhaps you should let the CI runs finish before making a new commit). Otherwise LGTM!

Use from __future__ import annotations so the unquoted forward
reference to IntegerModRing_generic (defined later in this module)
is safe at runtime, and resolve the annotation via
typing.get_type_hints in the doctest (review feedback from
vincentmacri).  Keep the collections.abc.Callable import at runtime
visibility: get_type_hints - used by the doctest contract and by
downstream stub generators - evaluates the annotation string in the
module namespace, so the name must exist there.  Exempt that import
from TC003 via per-file-ignores with a comment.
@starnotes-xj

Copy link
Copy Markdown
Contributor Author

@vincentmacri thanks — done in 581bf4d: the quotes are gone via from __future__ import annotations, so the unquoted forward reference to IntegerModRing_generic (defined later in the module) is safe. The doctest now resolves the annotation through typing.get_type_hints instead of touching the raw string.

One deliberate deviation from the suggested combination, with the reason: Callable stays a runtime import (not inside if TYPE_CHECKING). The annotation string is evaluated in the module namespace — by this file's own TESTS doctest and by downstream stub generators (typing.get_type_hints(IntegerModFactory)), which is exactly how sage-pycharm-stubgen prefers to read factory return types. With Callable confined to TYPE_CHECKING, get_type_hints raises NameError on that annotation (I reproduced this against an installed Sage 10.9 with the file overlaid). So the ruff typing-only rule TC003 is exempted for this one import via per-file-ignores, with a comment explaining why — mirroring the existing per-file F401 entries. Static resolution is unaffected: ty/pyright resolve both names (verified with mypy and with pyright 1.1.332, the version pinned in types.yml, plus current pyright).

This is the last planned commit — I won't push again unless review asks for something.

CI: the seven workflow runs generated for this head are already sitting in action_required again (they will expire without executing unless a maintainer approves them — that is what happened to the previous three rounds):

@sagemath/core — could someone approve these runs (or let me know if fork-based PRs can't be approved and I should move the branch into the main repo)? In the meantime the identical pull_request suite runs automatically on the same head in my fork with no approval gate — starnotes-xj/sage#1 — currently in progress for 581bf4d.

@vincentmacri @nbruin — happy to address anything else.

Comment thread pyproject.toml Outdated
Comment on lines +721 to +727
"src/sage/rings/finite_rings/integer_mod_ring.py" = [
# Callable must stay a runtime import (outside TYPE_CHECKING): the
# class-level __call__ annotation is resolved by typing.get_type_hints
# in the doctests and by downstream stub generators, so the name has
# to be present in the module namespace at runtime.
"TC003",
]

@vincentmacri vincentmacri Aug 17, 2026 •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I'd prefer for this to be a local noqa or ruff:ignore comment in src/sage/rings/finite_rings/integer_mod_ring.py than added to pyproject.toml.

Per review, keep the ruff exemption next to the import itself instead
of a per-file-ignores entry in pyproject.toml: the runtime visibility
of Callable is intentional (typing.get_type_hints resolves the
class-level __call__ annotation in the module namespace).
@starnotes-xj

Copy link
Copy Markdown
Contributor Author

@vincentmacri done — the pyproject.toml entry is gone; the exemption is now a local # noqa: TC003 on the Callable import itself, with a comment explaining that the runtime visibility is intentional (the class-level __call__ annotation is resolved by typing.get_type_hints in the module namespace — by this file's TESTS block and by downstream stub generators).

ruff passes in both --no-preview and --preview modes with the repo config.

This push (review-requested) regenerated the workflow runs, so they will again need a maintainer approval to execute — the approval links in my previous comment point to the now-outdated run set, but the same seven workflows are available for the current head on the Actions tab. The fork CI (starnotes-xj/sage#1) reruns automatically on the same head with no approval gate.

@vincentmacri

Copy link
Copy Markdown
Member

LGTM. I am okay with approving after the CI finishes on your fork.

@starnotes-xj

Copy link
Copy Markdown
Contributor Author

@vincentmacri — thanks for the LGTM. On the fork CI for the current head (4e2fa5a), every lane that has completed is green; the only failure is an infrastructure gap, not this PR:

lane result
Lint ✅ green
Static type check (ty + pyright) ✅ green
Build & Test (docker) — all four test shards, incl. src/sage/[g-o]* ✅ green (the ecl.pyx abort tracked in #42680 did not reproduce this round)
Build documentation (html) ❌ fails only at the Download old doc step — the fork has no develop baseline artifact to download (fork-infrastructure gap)
Build & Test using Meson / meson-minimal / Build documentation (PDF) ⏳ still running — I'll post the final results here

So the red lane is exactly the code-infrastructure issue: once the doc-baseline download works for fork CI (or that lane runs in the main repo where the artifact exists), this PR's CI is fully green — no failure is attributable to the changed code (finite_field_constructor.py, integer_mod_ring.py). From the code side, nothing else is needed.

Meanwhile the main-repo workflow runs for this head are still sitting in action_required (unexecuted). Either approving those runs or approving the PR on the fork-CI evidence works for me — just let me know which.

@starnotes-xj

Copy link
Copy Markdown
Contributor Author

@vincentmacri — the evidence that the only red lanes are code-infrastructure issues (not this PR) is in the earlier comments on this thread; pointing at them here for a quick look:

  1. The fork-CI verification table: on the identical head, the fork ran the entire pull_request suite — every lane green except (a) Build documentation (html), failing only at the Download old doc step because the fork has no develop baseline artifact to download, and (b) the docker lane's src/sage/libs/ecl.pyx abort.
  2. The ecl.pyx abort tracking: filed upstream as issue CI: src/sage/libs/ecl.pyx aborts (cysignals crash) against system libecl 24.5 on Python 3.14 — intermittent shard failure #42680 — it reproduces on branches that do not touch libs/ecl.pyx at all (and this round it did not even reproduce: all four docker test shards, including src/sage/[g-o]*, passed on 4e2fa5a).

So the only thing between this PR and fully green CI is that fork-side doc-baseline download. Once that infrastructure piece works for forks (or that lane runs in the main repo, where the artifact exists), the PR passes entirely — no failure is attributable to the two changed ring modules (finite_field_constructor.py, integer_mod_ring.py). If the doc-baseline fix is a workflow/config change rather than maintainer-only, I'm happy to prepare it.

@vincentmacri

Copy link
Copy Markdown
Member

Download old doc will work after it runs in your develop, so probably next time you merge upstream develop into your fork it will work after that. So that's fine.

Thank you for the contribution!

@starnotes-xj

Copy link
Copy Markdown
Contributor Author

@vincentmacri — the fork CI for 4e2fa5a has now fully finished. Final tally:

lane result
Lint ✅ green
Static type check (ty + pyright) ✅ green
Build & Test (docker) — all four test shards ✅ green
Build & Test with all meson features disabled ✅ green
Build documentation (PDF) ✅ green
Build & Test using Meson — 3.12 / 3.13 (ubuntu/macos/windows) + windows 3.14 ✅ green
Build & Test using Meson — ubuntu 3.14 / macos 3.14 ❌ one single doctest failure
Build documentation (html) ❌ Download old doc only (fork lacks the develop baseline artifact — self-heals once the fork runs develop)

The two failing 3.14 jobs fail with the same single doctest, in code this PR does not touch: src/sage/rings/valuation/limit_valuation.py, MacLaneLimitValuation._ge_[4] — valuations.LimitValuation(V[0], F) >= valuations.LimitValuation(V[1], F) raising AssertionError at limit_valuation.py:674 (assert self._G.gcd(other._G).is_one()). Both OSes, two different --random-seed values, identical failure — deterministic and specific to unix Python 3.14 (3.12/3.13 and windows 3.14 all pass). Full logs: https://github.com/starnotes-xj/sage/actions/runs/32054779216

So both remaining red lanes are upstream issues unrelated to the two ring modules this PR changes:

  • doc html: fork-side develop baseline artifact (as you noted, self-heals),
  • meson unix-3.14: the limit_valuation doctest failure above.

Nothing further is needed from the code side. Thanks again for the review!

@github-actions

Copy link
Copy Markdown

Documentation preview for this PR (built with commit 4e2fa5a; changes) is ready! 🎉
This preview will update shortly after each push to this PR.

@vbraun
vbraun merged commit 4dc4cad into sagemath:develop Aug 23, 2026
23 of 25 checks passed
starnotes-xj added a commit to starnotes-xj/sage that referenced this pull request Aug 23, 2026
FiniteField.from_integer, gen, multiplicative_generator and
random_element all return finite field elements.  Add
`-> FinitePolyExtElement` return annotations so static type checkers
can follow the element type after `F = GF(2^8, 'a')`, complementing
the factory return annotations of sagemath#42670.

FinitePolyExtElement is the common base of the three concrete element
classes (verified against Sage 10.9 for every backend):

- FiniteField_givaroElement      (implementation='givaro')
- FiniteField_ntl_gf2eElement    (implementation='ntl')
- FiniteFieldElement_pari_ffelt  (implementation='pari_ffelt')

Cython 3 retains annotations of def methods of cdef classes (e.g.
`_latex_` already carries `-> str` in this file), and the added
TESTS block verifies the runtime contract on all backends.
starnotes-xj added a commit to starnotes-xj/sage that referenced this pull request Aug 23, 2026
…uotientRing

Static type checkers cannot infer the return type of these module-level
constructor functions.  Add return annotations using the common base of
the concrete implementations (verified against Sage 10.9):

- PowerSeriesRing      -> PowerSeriesRing_generic (covers PowerSeriesRing_domain,
                          PowerSeriesRing_over_field and MPowerSeriesRing_generic)
- LaurentPolynomialRing -> LaurentPolynomialRing_generic (covers the
                          univariate and multivariate implementations)
- QuotientRing          -> QuotientRing_generic (covers the generic and
                          polynomial quotient implementations)

TESTS blocks assert the annotation against the runtime type for the
common univariate and multivariate cases.  Follow-up to sagemath#42670.
vbraun pushed a commit to vbraun/sage that referenced this pull request Oct 3, 2026
Release Manager
sagemathgh-42672: Annotate element-returning methods of FiniteField (follow-up to sagemath#42670)
    
Follow-up to sagemath#42670: the factory return annotations let static type
checkers infer the field type, but the chain breaks on the next step
because several element-returning methods of `FiniteField` have no
return annotation.

This PR adds `-> FiniteRingElement` to `from_integer`, `gen`,
`multiplicative_generator` and `random_element` in
`finite_field_base.pyx`.

`FiniteField` serves both extension fields and prime fields: extension-
field implementations return `FinitePolyExtElement` subclasses, while
prime fields return `IntegerMod` elements.  `FiniteRingElement` is the
common base of both families, so it is the sound return type for the
shared base-class methods.

The `TESTS` block checks the runtime contract for both `GF(29)` and
`GF(2^8, 'a')`, and verifies the exposed annotation.  These are
annotations only; factory and field behavior is unchanged.
    
URL: sagemath#42672
Reported by: 星记
Reviewer(s): Copilot
vbraun pushed a commit to vbraun/sage that referenced this pull request Oct 3, 2026
Release Manager
sagemathgh-42675: Annotate return types of PowerSeriesRing, LaurentPolynomialRing and QuotientRing (follow-up to sagemath#42670)
    
Follow-up to sagemath#42670: this PR annotates three constructor functions whose
return types static type checkers cannot infer.

- `PowerSeriesRing` returns `PowerSeriesRing_generic`, the common base
of its univariate and multivariate implementations.
- `LaurentPolynomialRing` returns `LaurentPolynomialRing_generic`, the
common base of its univariate and multivariate implementations.
- `QuotientRing` returns `Parent`: unlike the narrower generic quotient
class, this accurately covers all supported branches, including ordinary
and principal quotients, noncommutative quotients, Boolean-polynomial
implementations, integer quotients and the zero-ideal path that returns
the original parent.

Forward references are quoted locally where the implementation class is
defined later in the module, avoiding import-time `NameError` without
changing annotation evaluation semantics for unrelated functions.

Regression doctests cover representative runtime branches and
`typing.get_type_hints` resolution.  No runtime behavior changes; these
are annotations only.
    
URL: sagemath#42675
Reported by: 星记
Reviewer(s): Copilot
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.

7 participants