Skip to content

Fix set_rollback for non_atomic_requests views - #1

Closed
majidkhazaei wants to merge 19 commits into
adamchainz:fix_issue_6921_atomic_requestsfrom
majidkhazaei:fix-set-rollback-v2
Closed

majidkhazaei wants to merge 19 commits into
adamchainz:fix_issue_6921_atomic_requestsfrom
majidkhazaei:fix-set-rollback-v2

Conversation

@majidkhazaei

Copy link
Copy Markdown

Summary

This PR re-implements the core fix for encode#6921 on top of @adamchainz's
fix_issue_6921_atomic_requests branch, incorporating feedback from
the original PR's discussion.

Refs: encode#6921, encode#6922.

What this changes

  1. set_rollback(request=None) — Mirrors Django's
    BaseHandler.make_view_atomic() logic. When a request is
    provided, it reads the resolved view's _non_atomic_requests
    attribute and skips databases that were explicitly excluded from
    ATOMIC_REQUESTS.

  2. RemovedInDRF321Warning — The old no-arg signature is
    deprecated but still works (best-effort fallback to the previous
    behavior).

  3. exception_handler — Now passes context.get('request') to
    set_rollback().

  4. Tests:

    • NonAtomicViewUnderTestCaseTests — proper regression test using
      TestCase (not TransactionTestCase), addressing Copilot's
      feedback that the previous test didn't actually reproduce the bug.
    • SetRollbackDeprecationTests — verifies the deprecation warning.
    • SetRollbackWithoutResolverMatchTests — verifies the fallback
      when resolver_match is missing (APIRequestFactory).
    • Updated existing tests to pass a request argument.

Why this is different from the current state of encode#6922

  • Uses TestCase instead of TransactionTestCase for the regression
    test, so it actually fails without the fix.
  • Preserves backward compatibility via an optional argument and
    deprecation warning.
  • Best-effort fallback when resolver_match is unavailable.

Credit

Original design and analysis: @adamchainz.

Testing

All 11 tests in tests/test_atomic_requests.py pass. Pre-commit is green.

set_rollback() now mirrors Django's BaseHandler.make_view_atomic()
logic: when a request is provided, it reads the resolved view's
_non_atomic_requests attribute and skips databases that were
explicitly excluded from ATOMIC_REQUESTS. This prevents DRF from
marking outer transactions (e.g. Django's TestCase wrapper) for
rollback when an APIException is raised from a @non_atomic_requests
view.

The previous signature set_rollback() is deprecated and will emit
a RemovedInDRF321Warning. It falls back to the old
ATOMIC_REQUESTS + in_atomic_block behavior.

Refs encode#6921, encode#6922.
auvipy and others added 6 commits September 22, 2026 21:02
* Add regression test for OverflowError in unique validation

* Update tests/test_model_serializer.py

* Update tests/test_model_serializer.py

---------

Co-authored-by: James Cooke <jamescooke@users.noreply.github.com>
Co-authored-by: Bruno Alla <browniebroke@users.noreply.github.com>
Updates the requirements on [django-guardian](https://github.com/django-guardian/django-guardian) to permit the latest version.

Updates `django-guardian` to 3.5.0
- [Release notes](https://github.com/django-guardian/django-guardian/releases)
- [Commits](django-guardian/django-guardian@v2.4.0...3.5.0)

---
updated-dependencies:
- dependency-name: django-guardian
  dependency-version: 3.5.0
  dependency-type: direct:development
  dependency-group: optional
...

Signed-off-by: dependabot[bot] <support@github.com>
Bumps the github-actions group with 1 update: [codecov/codecov-action](https://github.com/codecov/codecov-action).


Updates `codecov/codecov-action` from 7.0.0 to 7.1.0
- [Release notes](https://github.com/codecov/codecov-action/releases)
- [Changelog](https://github.com/codecov/codecov-action/blob/main/CHANGELOG.md)
- [Commits](codecov/codecov-action@v7.0.0...v7.1.0)

---
updated-dependencies:
- dependency-name: codecov/codecov-action
  dependency-version: 7.1.0
  dependency-type: direct:production
  update-type: version-update:semver-minor
  dependency-group: github-actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
* Added test support for Python 3.15

* Formalized support for Python 3.15
@majidkhazaei

Copy link
Copy Markdown
Author

Hi @adamchainz, just a gentle ping on this.

Whenever you have a moment, I'd appreciate a review.

If there's anything you'd like me to adjust, or if you'd prefer
a different approach, just let me know. No rush at all.

Thanks!

dependabot Bot and others added 12 commits September 30, 2026 07:38
* Fix CI that broke due to latest Django bugfix

* Simplify comment
* Harden content negociation

* Add regression tests for content negotiation limits

* Remove redundant form media type test

* Remove comments about Django parser complexity

* Eliminate duplication in order_by_precedence

---------

Co-authored-by: Bruno Alla <alla.brunoo@gmail.com>
* Refuse charsets that are not text encodings

JSONParser decoded the request body with the charset the client named in its
Content-Type header, via codecs.getreader(). About 18 of the names
codecs.lookup() resolves are byte transforms rather than character sets, and
getreader() is the one entry point in codecs that does not consult
CodecInfo._is_text_encoding, so charset=bz2_codec wrapped the body in a
decompressor. Django charges DATA_UPLOAD_MAX_MEMORY_SIZE against the bytes that
arrived on the wire, and the expansion happens afterwards inside the parser,
where nothing counts it: 108 wire bytes became a 50,331,648-character value and
about 97 MiB of peak RSS.

The same header also reached eight uncaught exceptions, all unauthenticated
500s rather than 400s: charset=bz2_codec with a body that is not valid bz2
raises OSError out of JSONParser, charset=rot_13 raises TypeError, and any byte
transform raises LookupError out of FormParser and MultiPartParser when Django
decodes with it. So the reported amplification needed a crafted compressed
payload, while a plain garbage body was already enough to fault a worker.

Resolve the charset in one place instead, and reject anything that is not a
text encoding with a ParseError. All three parsers that decode text with the
value now go through it. FileUploadParser is left alone: it hands the encoding
to Django's upload handlers, which store it rather than decode with it.

A text encoding yields at most one character per byte, measured across all 113
of them, so the upload limit stays meaningful for every charset still accepted.
An unresolvable charset is also a ParseError now rather than a LookupError.
Django drops those before they reach a parser, so that only changes direct
parse() calls, and it changes them from a 500 to a 400.

* Follow the codebase conventions in comments and docs

No class docstring on the new test case, since no other class in
tests/test_parsers.py carries one, and the byte_transforms comment plus the
method names already say what it covers.

Hold the expected error message in a class attribute rather than a helper
method, matching TestDataUploadMaxMemorySize.expected_message in
tests/test_request.py, which is the class the other new test extends. Drop a
trailing comma that no other multi-line call in the module has.

Move the _is_text_encoding comment above the try block it explains rather than
inside it.

In the parsers docs, do not introduce a second PlainTextParser eight lines
above the Example section that already defines one. The snippet is now the
method body alone, which is also how the built-in parsers spell it.

* Incorporate changes from other fix for GHSA-wcg4-wch5-f3pj

* Streamline patch

---------

Co-authored-by: Bruno Alla <alla.brunoo@gmail.com>
* Make TokenProxy deletion actually delete the token

TokenProxy maps `pk` to the user id for the admin, but Django's deletion
collector identifies rows by `pk`, so the inherited `Model.delete()` and
any collected queryset delete matched the `key` column against a user id:
no row deleted, no error raised, and a token meant to be revoked still
able to authenticate. Delete through the concrete `Token` instead, on both
entry points -- `TokenProxy.delete()` and the proxy queryset's `delete()`
-- resolving the database alias the way the stock deletes do and refusing
the querysets `QuerySet.delete()` refuses. The `TokenAdmin.delete_model()`
workaround for the single-object case is now redundant and removed.

* Simplify TokenProxy queryset deletion

* Update docstring

* Fix some edge cases with deletion and multi-DB

* Clean-up tests aut token tests based on code review comments

---------

Co-authored-by: Bruno Alla <alla.brunoo@gmail.com>
…0071)

construct_search() maps 'pk' to the model's primary key field, but
must_call_distinct() passed 'pk' straight to Options.get_field(), so a view
with search_fields = ['pk'] (or a lookup through a relation such as
'author__pk') raised FieldDoesNotExist and returned a 500.

Resolve the alias in must_call_distinct() the same way construct_search()
does.
@majidkhazaei

Copy link
Copy Markdown
Author

Thanks @adamchainz. I've opened encode#10078.

This cross-fork PR is now superseded by encode#10078. I'll close it
to avoid confusion.

Thanks for your original work on this!

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.

9 participants