Skip to content

feat: list body and parameter errors together - #734

Merged
uniqueg merged 4 commits into
devfrom
feat/712-body-and-parameter-errors
Nov 7, 2026
Merged

uniqueg merged 4 commits into
devfrom
feat/712-body-and-parameter-errors

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 7, 2026 •

Copy link
Copy Markdown
Member

Closes #712

Summary

With Connexion 2, a request whose body and parameters are both invalid got errors for the body only, because Connexion validates the body before the parameters and stops there. This PR lists the body's fields and the parameters together in one 400, on Connexion 2, without waiting for Connexion 3.

  • How it works: Connexion wraps FOCA's BodyValidator directly around the function that FOCA's ParameterValidator returns. FOCA keeps a weak registry from that function to its validator. When the body is invalid (InvalidFieldsProblem), the body validator asks the parameter validator for the parameters' invalid fields and adds them after the body's.
    • The parameters are checked by FOCA only, so nothing is logged and no values are quoted.
    • Connexion's body validation runs around a stand-in function, so problems raised by the parameter validator or the handler are never mistaken for the body's.
  • Defaults stay backward compatible: title, status, detail (Connexion's message on the body's first error) and the exception class are unchanged. Only the entries in errors grow, and errors itself is new in 0.22.0 (feat: report invalid fields in 400 responses #711, not released yet). With exceptions.validation_reasons: false, detail names all listed fields, so it now includes the parameters too.
  • Edge cases, as documented:
    • With strict_validation, unknown parameters come first, as in the parameters-only path. If the declared parameters can't be listed, the unknown ones are still listed, as for ExtraParameterProblem.
    • Bodies rejected for other reasons (invalid JSON, unpaired surrogates) still get no errors.
    • For operations without declared parameters, unknown query parameters are listed only if the body is valid (StrictParametersResolver runs later).
    • Custom validators in the Connexion option validator_map keep the old behaviour.
  • Docs:

Verification

  • Tests written first, in tests/api/test_validation.py:

    • test_body_and_parameters: body and parameters listed together, with detail unchanged and no values in the logs. It failed before the change.
    • test_body_and_valid_parameters.
    • test_body_rejected_otherwise: invalid JSON plus invalid parameters gets no errors.
    • test_validators_collected: regression test for the registry leak found in review.
    • TestListingFails::test_body_and_parameters.
  • FOCA suite with MongoDB 7.0 (local mongod), on the branch before the test-only follow-up commit: 4872 passed, 3 skipped, and 2 failed:

    • test_apps_collected, an app-level version of the leak test that is order-dependent. It was replaced by test_validators_collected (see below), and tests/api passes (264).
    • test_release_notes on the #PR placeholder, fixed by the commit that sets the PR number (feat: list body and parameter errors together #734).
    • Coverage: 100%.
  • ruff, ruff format, mypy: passed. mkdocs build --strict: passed.

  • Downstream, against this branch, run with each repo's locked dependencies and Helm chart dependencies built:

    • proTES dev at a1ac9c7: 1722 passed, 11 skipped, 100% coverage.
    • cloud-registry dev at 31c7b8f: 2338 passed, 11 skipped, 100% coverage.
  • Review (full lane): adversarial-reviewer and quality-reviewer, two rounds.

    • Round 1, medium: the validator registry kept every app alive (strong values pointing back to their keys through the API). Fixed by storing weak references; regression test added.
    • Round 1, medium: duplicated strict-validation listing. Extracted into ParameterValidator._listed_by_foca.
    • Round 1, lows: a comment on the stand-in, a test for non-JSON bodies, and docs wrapping. Fixed.
    • Round 2: no high or medium findings. Unknown parameters are now listed even when the declared ones can't be, consistent with ExtraParameterProblem, and the validator_map caveat is documented.
  • FOCA suite on the final code (local MongoDB 7.0): 4874 passed, 3 skipped, 100% coverage.

  • CI on 2170555: all checks passed (CI passed, CodeQL, Read the Docs); image jobs skipped as intended on PRs.

  • Sourcery found three issues:

    • Parameter checks could replace the body's 400 if they raised. Fixed in 2653db1: listing is best effort, the body's fields are kept, and a warning is logged. Regression test TestListingFails::test_body_and_parameters_fail. tests/api and tests/errors pass (586), with 100% coverage of foca/api/validation.py.
    • The two other findings are declined, see below. All threads are answered and resolved.
  • CI on 2653db1: see the checks.

Declined review findings

  • Use a plain attribute on the wrapper instead of the registry: declined. functools.wraps copies __dict__ to every outer wrapper, so an attribute would also match functions that aren't the parameter validator's. The identity-keyed weak registry avoids that.

  • Sourcery: reserve part of the 100-entry limit for parameters: declined. The limit is documented, and entries are ordered with the body first, matching detail. A body with 100 or more invalid fields is an edge case, and the client sees the rest on its next attempt.

  • Sourcery: custom validator_map validators and operations without declared parameters aren't combined: intended and documented. Both keep the previous behaviour.

Follow-up (not blocking this PR)

  • Apps aren't collected after foca.api.routes._install_route_table ran for an earlier app in the same process: the per-app _RecordingApi class keeps a reference to its Flask app. This was seen in the test suite. It is older than this PR and only matters for processes that build many apps (tests).

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 2 commits November 7, 2026 11:57
With Connexion 2, the body is validated before the parameters, so a
request with an invalid body listed only the body's fields in `errors`.
FOCA's body validator now also lists the invalid parameters (checked by
FOCA only, without logging) after the body's fields, for operations whose
parameters FOCA's parameter validator checks. `detail` stays Connexion's
message on the body's first error.

Docs: invalid-request problem page, exceptions configuration, migration
guide and release notes for 0.22.0.

Closes #712

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The app-level check failed in the full suite, as another per-app
object (the route table API class of foca.api.routes) can keep apps
alive after earlier tests; check the validator registry directly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

API

Extend invalid-body responses to append FOCA-validated parameter errors while preserving body-first detail and best-effort behavior.

  • foca/api/validation.py L93-156, L191-198, L386-434 (+3 small edits)

Documentation

Explain how body and parameter errors are combined, including ordering, limitations, and compatibility in user-facing documentation and release notes.

  • docs/configuration/exceptions.md L131-132
  • docs/migration-0.22.md L191-194
  • docs/problems/invalid-request.md L110-127
  • docs/releases/0.22.0.md L7-10

Tests

Test combined error reporting, edge cases, and that the weak validator registry does not retain validators.

  • tests/api/test_validation.py L3-6, L701-767, L1010-1036

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

@codecov

codecov Bot commented Nov 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (82e4802) to head (2653db1).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #734   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           74        74           
  Lines         9343      9373   +30     
=========================================
+ Hits          9343      9373   +30     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review November 7, 2026 11:29

@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 found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="foca/api/validation.py" line_range="148" />
<code_context>
+            try:
+                check_body(request)
+            except InvalidFieldsProblem as exc:
+                errors = parameters.field_errors(request)
+                if errors:
+                    exc.field_errors = (*exc.field_errors, *errors)
</code_context>
<issue_to_address>
**Parameter checks can mask body errors**

When the body is invalid and parameter extraction or validation raises while FOCA tries to list parameter errors, `parameters.field_errors(request)` runs outside a guard, and `_listed_by_foca()` calls parameter extraction and validation methods that can raise before `_list_fields()` handles field-listing failures. That exception replaces the original `InvalidFieldsProblem`, so a request that previously received a 400 for its invalid body can instead fail with an unhandled error.

Make parameter-field collection best-effort at the body-error boundary so a failure to inspect parameters preserves the original body `InvalidFieldsProblem`.
</issue_to_address>

### Comment 2
<location path="foca/api/validation.py" line_range="150" />
<code_context>
+            except InvalidFieldsProblem as exc:
+                errors = parameters.field_errors(request)
+                if errors:
+                    exc.field_errors = (*exc.field_errors, *errors)
+                raise
+            return function(request)
</code_context>
<issue_to_address>
**Parameter errors disappear behind body errors**

When the body has at least 100 invalid fields and one or more parameters are invalid, `schema_field_errors()` caps the body errors at `MAX_FIELD_ERRORS` (100), and response serialization applies the same cap to the combined list, so a body with 100 or more invalid fields consumes the entire limit and the caller sees none of the invalid parameters in `errors`.

Apply a combined error budget that reserves entries for parameter errors, or otherwise make the truncation policy preserve representation from both sources.
</issue_to_address>

### Comment 3
<location path="foca/api/validation.py" line_range="124" />
<code_context>
+        reference = _parameter_validators.get(function)
+        parameters = reference() if reference is not None else None
+        if parameters is None:
+            return super().__call__(function)
+        # Connexion's validation of the body, around a stand-in that does
+        # nothing, so that only the body's problems are caught below, not
</code_context>
<issue_to_address>
**Some parameter errors remain separate**

The body validator combines parameter errors only when the wrapped function is registered with FOCA's `ParameterValidator`; otherwise it falls back to Connexion's body validation. Thus custom `validator_map` validators, and strict unknown query parameters for operations without declared parameters, are not included with body errors.
</issue_to_address>

Linked issues

#712 feat: list body and parameter errors together · 1 of 2 met

# Requirement Status Notes
1 Collect the body and parameter field errors in one 400 response. 🟡 Partly met The default FOCA parameter-validator path combines them, but custom validator_map validators are not combined, and strict unknown query parameters for operations without declared parameters are only listed when the body is valid.
2 Remove the documented limit on collecting body and parameter errors together. ✅ Met The invalid-request documentation now describes collecting body and parameter errors together, with the remaining edge cases noted.

Sourcery assessment

Approval pending. 3 findings to address first.

Blocking findings: foca/api/validation.py:148, foca/api/validation.py:150, foca/api/validation.py:124


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread foca/api/validation.py Resolved
Comment thread foca/api/validation.py Resolved
Comment thread foca/api/validation.py Resolved
Listing the parameters of a request with an invalid body is best
effort: if it raises, the body's fields are listed alone and a warning
is logged, instead of the error replacing the 400 (Sourcery).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 3831f0e into dev Nov 7, 2026
64 of 83 checks passed
@uniqueg
uniqueg deleted the feat/712-body-and-parameter-errors branch November 7, 2026 11:43
@uniqueg uniqueg added this to the v0.22.0 milestone Nov 9, 2026
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.

feat: list body and parameter errors together

1 participant