Skip to content

Close the six follow-up issues, and make pyright the single type checker - #42

Merged
zedrdave merged 18 commits into
mainfrom
chore/repo-health
Aug 14, 2026
Merged

zedrdave merged 18 commits into
mainfrom
chore/repo-health

Conversation

@zedrdave

Copy link
Copy Markdown
Member

Supersedes #41, which was opened when this branch only implemented the plan. It has since grown a second half, so this PR replaces it with an accurate description.

Part 1: the six tracked follow-up issues

Commit Item
66994af d4a7b29 470d52c POST honours arg_schema for the request body while schema stays the response schema. INDEX is deliberately deferred and the reason is now recorded in docs/crud.rst.
3bb7da7 cf6d0af ruff 0.8.6 to 0.16.2, BaseRoleEnum to enum.StrEnum, docs typo, contributor bootstrap.
89e1d28 scripts/bump_version.sh fails loudly on a bad substitution.
a413445 Bandit removed; ruff's S ruleset is the security lint.
6b9b539 Python 3.13 and 3.14 in the matrix and classifiers; action pins refreshed.

The arg_schema work took three commits because implementing it exposed two further defects, both caught by review rather than by the suite:

  1. The handler assumed the payload was a model instance. With a plain marshmallow.Schema it wrote a key into the payload dict and returned 200 having persisted nothing. That was the pre-existing behaviour for any plain POST schema, not only for arg_schema.
  2. Building the model from the payload then rejected any field the model does not define, so the documented invite-only signup went from silently doing nothing to raising TypeError. Unknown fields are now validated and dropped, which is what marshmallow-sqlalchemy already does for a model-bound schema.

Part 2: type checking and repository health

Commit Change
1a13c41 87a7c25 Remove the pyright suppressions on the CRUD decorators by fixing their cause: conditionally-assigned optionals, and two get definitions in one class body. One index implementation now serves the paginated and non-paginated cases.
d781bc6 Performance monitoring settings are resolved per app instead of captured from whichever app registered the Engine hooks first.
6e1676c mypy removed; pyright is the only type checker. reportUnnecessaryTypeIgnoreComment replaces warn_unused_ignores and flagged 88 dead suppressions.
e649a36 reportMissingParameterType and reportMissingTypeArgument enabled, which is what mypy's disallow_untyped_defs and disallow_incomplete_defs were buying. All 177 sites annotated, no rule disabled, no suppression added.
d5b49fe Delete the stubs/ tree and fix the pyright config.
924764e CHANGELOG, arg_schema docs for POST, and stale comment cleanup.

Two of these deserve attention.

The performance monitoring fix is a real bug, not test hygiene. The Engine event listeners are registered once on the class, but the thresholds were captured from the first app to register. A second app's SQLALCHEMY_SLOW_QUERY_THRESHOLD did nothing, and an app that never enabled SQLALCHEMY_PERFORMANCE_MONITORING was still monitored and still had its queries counted. It surfaced as an intermittent test failure that passed in isolation.

The stubs/ tree was dead. stubPath was "./stubs;./stubs/test_stubs"; pyright takes a single directory, reported it as invalid and ignored the tree, so none of those .pyi files had ever been consulted. Pointing stubPath at stubs/ instead produced 16 errors, because the tree is partial: there is no defaults.pyi, so the models it re-exports resolve to Unknown. The package ships py.typed, the stubs are not in the wheel, and they duplicated an inline-typed package they had already drifted from. pythonVersion = "3.11" is now set too, so local runs check the declared floor rather than whatever interpreter is installed.

Compatibility

BaseRoleEnum is public and its string form changes: str(role), f-strings and %s now produce ADMIN rather than BaseRoleEnum.ADMIN. Comparisons, .value, JSON output and stored values are unchanged. This is in the CHANGELOG under Changed.

Verification

401 tests pass on 3.11 through 3.14. pyright reports 0 errors and 0 warnings, with the stubs no longer masking the real types. ruff check and format are clean, pre-commit passes, both workflow files parse, and poetry build produces a wheel. Coverage is 87%.

The Codecov upload fails with Token required - not valid tokenless upload. That is pre-existing, reproduced on main with codecov-action v4, and hidden by fail_ci_if_error: false. It needs a CODECOV_TOKEN repository secret; the files rename in this PR is verified working by the log line Found 1 coverage files to report.

Still unverified: the build to publish artifact round trip, since those jobs only run on a release or a manual dispatch.

MethodConfig["arg_schema"] was documented for POST but silently ignored;
the endpoint used "schema" for both request input and response output.

Resolve post_input_schema and post_response_schema before the GenericIndex
class body so the decorators can reference them. When arg_schema is present
it is used as the input schema; schema continues to be the response schema.
When arg_schema is absent the behaviour is unchanged (schema for both).

Add tests/integration/test_arg_schema.py covering:
- POST arg_schema: valid input accepted, invalid secret rejected (422),
  missing required field rejected (422), response uses schema not arg_schema
- POST without arg_schema: backwards-compatible (schema for both)
- PATCH arg_schema: valid payload accepted, unknown fields rejected (422)
- pyproject.toml: ruff ^0.8.5 -> ^0.16.2; drop the UP038 ignore (rule removed)
- base_roles.py: UP042 fix, BaseRoleEnum(str, enum.Enum) -> enum.StrEnum.
  Behaviourally inert: every path uses .value or plain-str comparison before
  roles reach serialisation, the sa.String(50) column, or query filters.
- base_roles.pyi: stub follows, with real member values instead of plain str
- docs/user-models.rst: BaseRoleEnum.MODERATOR does not exist, use USER
- CONTRIBUTING.md: single bootstrap step, poetry install --sync plus
  pre-commit install
- reformat tests/unit/test_version.py and tests/integration/test_arg_schema.py
  under the new formatter and RUF059
The sed calls were unchecked: a non-matching pattern exits 0 and slips past
set -e, then the script printed "updated" unconditionally. tests/unit/
test_version.py runs before the bump, so it only catches the breakage on the
next run.

- assert the rewritten line exists (anchored on __version__ = "$NEW_VERSION")
  and exit 1 otherwise; the success echo now follows the assertion
- drop the README badge substitution: it has matched nothing since the ?v=
  markers were removed in f317efd, and a broadened pattern would corrupt the
  sample JSON in README.md
- collapse the macOS/Linux branch: [0-9][0-9]* is valid POSIX BRE under BSD
  and GNU sed, so only the -i argument differs
- read the new version with poetry version -s instead of parsing awk field 6
Bandit had five config sources and three were dead: it only reads
[tool.bandit] when passed -c pyproject.toml (no invocation did), and the root
.bandit file is never discovered when the scan target is flask_more_smorest/.
Only the tox env's inline -s list had any effect. The scan itself reports zero
issues, and ruff's S ruleset already covers both flask_more_smorest and tests
with correct per-file ignores.

Removed: the dev dependency, the lint-job step, the standalone security job
(build now needs [test, lint]), the tox security env, [tool.bandit], the
pre-commit hook, and the .bandit file.
The package allows >=3.11,<4.0 but CI only tested 3.11 and 3.12, and local
development already runs 3.14. Add 3.13 and 3.14 to the test matrix and the
classifiers. mypy python_version stays at 3.11: it tracks the supported floor,
not the development interpreter.

Bump the actions off the deprecated Node 20 runtime: checkout v4 -> v5,
setup-python v5 -> v6 (v4 in pre-commit.yml), cache v4 -> v5,
upload-artifact and download-artifact v4 -> v5, codecov-action v4 -> v5.
codecov-action v5 dropped the `file` input, so rename it to `files` in the
same change; with fail_ci_if_error false, a bare bump would have stopped the
coverage upload silently.

Pin snok/install-poetry to 2.4.1 instead of `version: latest` so builds are
reproducible.
poetry install --sync is deprecated in Poetry 2.x and prints a removal
warning.
Honouring arg_schema for POST exposed a gap in the handler: it called
new_object.update(commit=True), which only creates a row when the input
schema is model-bound (load_instance=True). A plain marshmallow schema, the
usual case for an explicit arg_schema, deserialises to a dict, so update()
just wrote a key into that dict and the endpoint returned 200 without
persisting anything. Build the model instance when the payload is a dict.

The POST response schema is again passed through untouched, as GET and PATCH
do, so a configured Schema instance keeps its options instead of being
collapsed to its class.

Tests now assert the row is persisted, and cover a model-bound arg_schema.

Also sweep the docs and config left stale by this series: .github/AGENTS.md
still described the removed README badge step, the deleted bandit job and a
3.11/3.12 matrix; the bump script banner repeated the same claims; the tox
envlist now matches the CI matrix.
The ignores were hiding a declaration problem, not a real type conflict.
post_input_schema and post_response_schema were pre-declared as None and
assigned under a guard, so both stayed Optional; pyright cannot narrow a
captured variable inside the nested class body, and the decorators then
looked like they received None. Resolve both from
config.methods.get(POST, {}) instead, which yields non-optional types and
needs no suppression.

Narrow the payload with isinstance(new_object, dict) rather than a negative
check against the model_cls variable, which pyright cannot use for narrowing:
that one was a genuine reportCallIssue on the ** expansion.

pyright is now down to the pre-existing reportRedeclaration on the paginated
and non-paginated index handlers.
The paginated and non-paginated index handlers were two `get` definitions in
one class body, which is what pyright flagged: the second declaration
obscures the first. They differed only in the paginate decorator and in
whether the query was limited.

Keep one implementation, taking pagination_parameters as an optional
argument, and compose the decorator stack instead: paginate is applied only
when the blueprint has a default page size. This also drops the four
suppressions on the index decorators, since index_schema_class and
query_filter_schema are no longer conditionally-assigned optionals.

pyright is now clean across flask_more_smorest and tests.

Add coverage for the branch that had none: default_page_size=None returns
every row with no pagination header, and page/page_size stay inert because
they come from the filter schema rather than the paginate decorator.
The Engine event listeners are registered once on the Engine class, but the
thresholds were captured from whichever app registered them first. Every
later app silently inherited that first configuration, so a second app's
SQLALCHEMY_SLOW_QUERY_THRESHOLD did nothing, and an app that never enabled
monitoring was still monitored and still had its queries counted.

Resolve the settings from the app handling each query instead, falling back
to the registering app's values when there is no app context. Monitoring is
now off for any app that did not opt in.

This is what made test_slow_query_threshold_configurable fail intermittently
in full-suite runs: a fixture registered a 0.001s threshold, so any later
SELECT that took longer than a millisecond logged a slow query the test did
not expect. It passed in isolation because nothing had registered first.

Add two tests that fail without the fix: one app's threshold must not leak
into another, and an app without monitoring must stay unmonitored.
Both checkers ran over the same code with overlapping configuration. Pyright
was already a dev dependency, is the checker the stubs/ directory targets,
and it caught two real errors mypy missed in this series. Keeping one is
enough.

Removed: the mypy dependency, [tool.mypy] and its two override tables,
tests/mypy.ini, scripts/mypy.sh, the tox mypy env, and the mypy steps in CI,
pre-commit and the release script. Pyright takes their place, with
scripts/pyright.sh as the entry point named in AGENTS.md.

Enable reportUnnecessaryTypeIgnoreComment, which replaces mypy's
warn_unused_ignores. It flagged 88 dead suppressions, all removed. The
remaining mypy-style comments are now rule-scoped pyright ignores: a bare
"# type: ignore" suppresses everything on the line for pyright too, so
leaving them would have hidden real errors. The five warnings they were
masking are now explicit.
These two rules are what mypy's disallow_untyped_defs and
disallow_incomplete_defs were buying, and pyright's standard mode leaves them
off. Turning them on surfaced 177 sites: 43 in the package, 134 in the tests.
All are fixed with real annotations; no rule was disabled and no suppression
was added (the ignore count is unchanged at 62, and the one that moved did so
because the formatter rewrapped its signature).

Notable choices:

- exceptions.py: debug context was dict[str, str | int | bool | dict | None],
  whose inner dict was unparameterised. It is now a recursive DebugContext
  alias built on Mapping/Sequence, which is covariant, so the nested
  dict[str, str | None] values the code actually stores still fit.
- SQLAlchemySchema and SQLAlchemyAutoSchema are generic over the model type.
  Schemas here are built per model at runtime by create_model_schema, so the
  parameter is Any rather than a model that the factory cannot carry.
- db.session is scoped_session[flask_sqlalchemy.session.Session], not
  sqlalchemy.orm.Session; the test fixtures now say so.
- The db_session fixture yields None, and its annotation now says that.
- Permission hooks in tests take user: Any, matching _can_read/_can_write in
  the library.
An arg_schema exists to accept an input shape that differs from the model,
which is exactly what the documented invite-only signup does: it validates an
invite_code that is not a column. Passing the deserialised dict straight to
the declarative constructor raised TypeError, so the documented configuration
went from silently doing nothing to returning 500.

Keys the model does not define are now dropped, mirroring what
marshmallow-sqlalchemy already does for a model-bound schema. The new test
uses the documented shape and fails with TypeError without this change.
stubPath was "./stubs;./stubs/test_stubs". Pyright takes a single directory,
so it reported "not a valid directory" and silently ignored the whole tree:
every .pyi in it has been dead since it was added, including the base_roles
stub this branch edited.

Pointing stubPath at stubs/ made pyright resolve the package through those
stubs instead of the source and produced 16 errors, because the tree is
partial: there is no defaults.pyi, so the models it re-exports became
Unknown. The package ships py.typed, the stubs are not in the wheel, and they
duplicate an inline-typed package they had already drifted from, so they go.

Also set pythonVersion = "3.11". Pyright was inferring the language level
from the interpreter, so local runs checked 3.14 while CI checked 3.11 and
the declared floor is 3.11.
- CHANGELOG: the Unreleased section was empty while this branch changed four
  user-visible behaviours, including the BaseRoleEnum string form.
- docs/crud.rst: arg_schema was only shown on PATCH. Document it for POST,
  state that unknown fields are dropped, and name the INDEX fork that plan
  item 6 deferred, so the reason it is unimplemented is recorded.
- database.py: the "monitoring enabled" line printed the registering app's
  threshold as if it were global; say which app it belongs to.
- user_context.py: the cast comment referred to mypy, which is gone.
- pyproject: list pyright with the other code-quality tools, not under docs.
Strict is achievable here, and reaching it fixed real defects rather than
just adding annotations:

- error_handlers.py checked `db.session is not None`, which never holds:
  accessing the session raises RuntimeError when init_db was not run, and
  that exception would have masked the database error being handled. It is
  now suppressed explicitly.
- base_model.__init__ repeated the same impossible None check after already
  catching that RuntimeError.
- UserBlueprint tested `model is not None` and `methods is not None` after
  both had been assigned defaults.
- Two casts were redundant, and `import uuid` plus a TYPE_CHECKING import of
  Blueprint were unused.
- can_read() compared `self.id` to None to detect an unsaved object, which
  the checker calls dead because the mapped column is not optional. It is
  read through getattr with a default, keeping the runtime behaviour exactly:
  this is a permission path, so it is not the place to change semantics.

Three rules are disabled with the reason recorded in pyproject.toml, each a
mismatch between the rule and this codebase rather than a defect:
reportUnnecessaryIsInstance (the public API validates caller input, and
annotations are not enforced at runtime for untyped callers),
reportUnusedFunction (callbacks registered by decorator are never referenced
by name), and, for tests only, reportPrivateUsage and reportUnusedClass
(tests exercise the _can_* hooks and define models inside fixtures).

reportPrivateUsage stays on for the package, so the four existing sites are
justified inline instead: two reach into marshmallow-sqlalchemy and
flask-jwt-extended internals that have no public equivalent, and two use this
library's own _can_write hook for cross-model delegation.

The reportUnknown* family stays off, as it already was. flask-smorest,
marshmallow-sqlalchemy and flask-jwt-extended ship no type information, so
enabling it reports 220 partially-unknown results in the package and 284 in
the tests, none of them defects here.

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 closes multiple follow-up issues by (1) fixing CRUD POST request-body schema handling (arg_schema), (2) correcting SQLAlchemy performance monitoring to resolve settings per Flask app, and (3) consolidating repository type checking on pyright (removing mypy, bandit, and unused stubs), alongside related CI/docs/test updates.

Changes:

  • Implement POST arg_schema semantics (input vs output schema) and add/adjust integration tests for CRUD/index behavior.
  • Fix SQLAlchemy Engine performance monitoring so thresholds/settings are read per-app per-query (and add coverage for multi-app scenarios).
  • Remove mypy/bandit/stubs and standardize on strict pyright with updated scripts, configs, and CI/pre-commit tooling.

Reviewed changes

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

Show a summary per file
File Description
tests/unit/test_version.py Simplifies version mismatch assertion formatting.
tests/unit/test_user_model_schema.py Adds explicit typing for fixtures/params.
tests/unit/test_user_context.py Adds explicit typing for fixtures/params.
tests/unit/test_user_blueprint.py Tightens typing for SQLAlchemy session fixtures and test signatures.
tests/unit/test_testing_helpers.py Tightens typing for SQLAlchemy session fixtures and test signatures.
tests/unit/test_schema_resolver.py Switches ignores to pyright-specific ignore codes.
tests/unit/test_query_filtering.py Adds typing for fixtures and model parameters.
tests/unit/test_polymorphic_inheritance.py Adds typing for fixtures/params.
tests/unit/test_perms_model.py Removes mypy-era ignores and adjusts pyright suppressions.
tests/unit/test_performance_monitoring.py Adds multi-app monitoring regression tests.
tests/unit/test_pagination.py Removes mypy-era ignores and updates pyright suppressions.
tests/unit/test_health_endpoint.py Adds typing for app fixture param.
tests/unit/test_has_domain_access.py Adds typing for fixtures/params.
tests/unit/test_exceptions.py Converts type ignores to pyright equivalents.
tests/unit/test_custom_getter.py Updates typing/pyright ignores for dynamic test models.
tests/unit/test_crud_methods_logic.py Converts type ignores to pyright equivalents.
tests/unit/test_crud_blueprint.py Converts type ignores to pyright equivalents.
tests/mypy.ini Removes mypy test configuration.
tests/integration/test_user_perms.py Tightens typing for session fixtures and optional access suppressions.
tests/integration/test_user_fully_extended.py Removes mypy-era ignores and improves return/param typing.
tests/integration/test_user_demoapp_integration.py Improves typing for schema generics and endpoint signatures; updates pyright ignores.
tests/integration/test_user_defaults.py Removes mypy-era ignores; keeps runtime placeholders typed.
tests/integration/test_sqla_integration.py Adds typing for permission hook params.
tests/integration/test_maximal_app.py Tightens typing for session fixtures and suppressions for dynamic models.
tests/integration/test_crud_integration.py Adds pagination/index behavior tests and shared permission hook helper.
tests/integration/test_arg_schema.py New integration coverage for POST/PATCH arg_schema behavior and persistence.
stubs/test_stubs/integration/test_user_mixed_defaults.pyi Removes unused/unapplied stub file.
stubs/flask_more_smorest/perms/models/base_roles.pyi Removes unused/unapplied stub file.
stubs/flask_more_smorest/perms/models/abstract_user.pyi Removes unused/unapplied stub file.
stubs/flask_more_smorest/perms/models/abstract_token.pyi Removes unused/unapplied stub file.
stubs/flask_more_smorest/perms/models/abstract_setting.pyi Removes unused/unapplied stub file.
stubs/flask_more_smorest/perms/models/abstract_role.pyi Removes unused/unapplied stub file.
stubs/flask_more_smorest/perms/models/init.pyi Removes unused/unapplied stub file.
stubs/flask_more_smorest/perms/model_mixins.pyi Removes unused/unapplied stub file.
stubs/flask_more_smorest/perms/init.pyi Removes unused/unapplied stub file.
scripts/pyright.sh Adds a dedicated pyright runner script.
scripts/mypy.sh Removes mypy runner script.
scripts/bump_version.sh Switches release checks to pyright; improves sed portability and loud failure behavior.
pyproject.toml Removes mypy/bandit config, enables strict pyright rules, updates tox envs, bumps ruff/pyright versions, expands supported Python classifiers.
poetry.lock Updates lockfile for dependency/tooling changes (ruff/pyright, bandit/mypy removal, poetry version).
flask_more_smorest/sqla/schema.py Updates SQLAlchemyAutoSchema typing to include generic parameter.
flask_more_smorest/sqla/database.py Fixes performance monitoring to resolve settings per-app per-query with fallback behavior.
flask_more_smorest/sqla/base_model.py Improves typing for mapper properties and session-init checks; adjusts pyright suppressions.
flask_more_smorest/perms/user_registry.py Tightens typing of registry state and app-state helpers.
flask_more_smorest/perms/user_context.py Removes redundant cast and improves type narrowing logic.
flask_more_smorest/perms/user_blueprint.py Adjusts registration/public-registration logic and request typing.
flask_more_smorest/perms/perms_blueprint.py Improves decorator callable typing and pyright suppressions for marker attributes.
flask_more_smorest/perms/models/user.py Removes unnecessary cast around typed get_current_user.
flask_more_smorest/perms/models/base_roles.py Switches BaseRoleEnum to enum.StrEnum.
flask_more_smorest/perms/model_mixins.py Adds pyright suppressions for declarative attrs and permission-hook protocol use.
flask_more_smorest/perms/jwt.py Adds typing and pyright suppression for private flask-jwt-extended API usage.
flask_more_smorest/perms/base_perms_model.py Improves persisted-id check and typing of recursive create-check helper.
flask_more_smorest/perms/api.py Tightens typing for spec kwargs and public/admin marker attribute writes.
flask_more_smorest/error/exceptions.py Introduces a typed debug-context alias for structured debug data.
flask_more_smorest/error/error_handlers.py Ensures rollback does not mask original DB errors when DB isn’t initialized.
flask_more_smorest/crud/query_filtering.py Tightens typing for schema post-load hook and filter input mapping.
flask_more_smorest/crud/pagination.py Updates pyright suppressions for mixin-super and metadata fields.
flask_more_smorest/crud/crud_blueprint.py Implements POST arg_schema input vs response schema; unifies index view implementation.
flask_more_smorest/crud/blueprint_operationid.py Tightens typing around route/add_url_rule and parameters.
flask_more_smorest/init.py Removes unused imports and TYPE_CHECKING artifacts.
docs/user-models.rst Fixes role enum example in docs.
docs/crud.rst Documents POST arg_schema semantics and explicitly defers INDEX behavior.
CONTRIBUTING.md Updates contributor bootstrap instructions and replaces mypy with pyright.
CHANGELOG.md Adds detailed unreleased notes for arg_schema, monitoring fix, and tooling changes.
AGENTS.md Updates agent instruction to run pyright (single type checker).
.pre-commit-config.yaml Replaces mypy/bandit hooks with a pyright hook.
.github/workflows/pre-commit.yml Updates action versions and pins Poetry version.
.github/workflows/ci-cd.yml Expands Python test matrix, removes security job, runs pyright in lint, updates action versions and Codecov input.
.github/AGENTS.md Updates release instructions to pyright and reflects CI pipeline changes.
.bandit Removes bandit configuration file.

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

Comment thread flask_more_smorest/error/exceptions.py Resolved
The upload has been failing with "Token required - not valid tokenless
upload" on every run, including on main before this branch, and
fail_ci_if_error: false meant nobody saw it. It needs a Codecov account and
an upload token, which this project is not adopting.

Coverage still runs in CI and prints term-missing in the test log; only the
xml report, which existed solely to feed the upload, is gone.
Review feedback on #42. SQLAlchemy's declarative constructor admits any
attribute the class has, so filtering the payload on existence alone let a
field named after a method, such as update, be set on the instance. That
shadows the bound method and the very next line, new_object.update(...),
fails with "'str' object is not callable".

Exclude callables. Columns, relationships, hybrids and property setters are
all non-callable, so nothing legitimate is lost; filtering to mapped
attributes instead would have silently dropped hybrid and property fields.

Also spell the recursive DebugContextValue alias with only its recursive
references quoted, so it is a union object at runtime rather than a string.
@zedrdave
zedrdave merged commit a88a2b2 into main Aug 14, 2026
9 checks passed
@zedrdave
zedrdave deleted the chore/repo-health branch August 14, 2026 15:28
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.

2 participants