Repository navigation
feat: list body and parameter errors together - #734
Conversation
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]>
Reviewer's GuideAPIExtend invalid-body responses to append FOCA-validated parameter errors while preserving body-first detail and best-effort behavior.
DocumentationExplain how body and parameter errors are combined, including ordering, limitations, and compatibility in user-facing documentation and release notes.
TestsTest combined error reporting, edge cases, and that the weak validator registry does not retain validators.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
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]>
Closes #712
Summary
With Connexion 2, a request whose body and parameters are both invalid got
errorsfor 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 one400, on Connexion 2, without waiting for Connexion 3.BodyValidatordirectly around the function that FOCA'sParameterValidatorreturns. 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.title,status,detail(Connexion's message on the body's first error) and the exception class are unchanged. Only the entries inerrorsgrow, anderrorsitself is new in 0.22.0 (feat: report invalid fields in 400 responses #711, not released yet). Withexceptions.validation_reasons: false,detailnames all listed fields, so it now includes the parameters too.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 forExtraParameterProblem.errors.StrictParametersResolverruns later).validator_mapkeep the old behaviour.docs/problems/invalid-request.md("What is collected": removes the documented limit and describes the order and edge cases);docs/configuration/exceptions.md;docs/migration-0.22.md;docs/releases/0.22.0.md: a## Featuresentry for invalid fields in400responses. feat: report invalid fields in 400 responses #711 had no entry yet, so this one entry covers feat: report invalid fields in 400 responses #586/feat: report invalid fields in 400 responses #711 and this PR.Verification
Tests written first, in
tests/api/test_validation.py:test_body_and_parameters: body and parameters listed together, withdetailunchanged 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 noerrors.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 bytest_validators_collected(see below), andtests/apipasses (264).test_release_noteson the#PRplaceholder, fixed by the commit that sets the PR number (feat: list body and parameter errors together #734).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:
devat a1ac9c7: 1722 passed, 11 skipped, 100% coverage.devat 31c7b8f: 2338 passed, 11 skipped, 100% coverage.Review (full lane): adversarial-reviewer and quality-reviewer, two rounds.
ParameterValidator._listed_by_foca.ExtraParameterProblem, and thevalidator_mapcaveat 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:
TestListingFails::test_body_and_parameters_fail.tests/apiandtests/errorspass (586), with 100% coverage offoca/api/validation.py.CI on 2653db1: see the checks.
Declined review findings
Use a plain attribute on the wrapper instead of the registry: declined.
functools.wrapscopies__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_mapvalidators and operations without declared parameters aren't combined: intended and documented. Both keep the previous behaviour.Follow-up (not blocking this PR)
foca.api.routes._install_route_tableran for an earlier app in the same process: the per-app_RecordingApiclass 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