Skip to content

fix: undo changes of failed middlewares - #318

Merged
uniqueg merged 3 commits into
devfrom
fix/middleware-alternatives
Oct 24, 2026
Merged

uniqueg merged 3 commits into
devfrom
fix/middleware-alternatives

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 24, 2026 •

Copy link
Copy Markdown
Member

Summary

Alternatives of a middleware step share one request. An alternative that changed the JSON body and then failed left its partial changes for the next alternative. The handler now takes a snapshot of the body for steps with more than one alternative and restores it in place after each failed alternative (not after the last one, which raises anyway). The docs say plainly that only the JSON body is restored: not headers, environ or request attributes, and not a body that was replaced instead of changed. #315 replaces this mechanism with a copy of the task per alternative.

Verification

Run locally:

  • ruff, ruff format, mypy, ast-grep (and its rule tests), semgrep: passed
  • pytest: 1037 passed, 80 skipped (chart and real-MongoDB tests), 100% coverage; the new tests include two failing alternatives in a row and a nested body
  • mkdocs build --strict: passed

Reviewed with the adversarial and quality reviewer subagents: no high or medium findings. Both low findings are fixed (snapshot only when there are alternatives; docs on what is restored).

Not run locally: the Docker Compose smoke test and the MongoDB 7.0 CI entry.

Open questions

None.

Closes #313

🤖 Generated with Claude Code

Summary by Sourcery

Isolate middleware alternatives by restoring the request JSON body after failed attempts.

Bug Fixes:

  • Restore in-place JSON body changes made by a failed middleware before trying the next alternative.

Enhancements:

  • Document the scope and limitations of request-body restoration during middleware fallback.

Documentation:

  • Clarify that only in-place JSON body changes are restored, while headers, environment, request attributes, and replaced bodies remain unchanged.

Tests:

  • Add coverage for consecutive failing alternatives, nested body changes, and non-object JSON bodies.

uniqueg and others added 2 commits October 24, 2026 23:59
Alternatives of a middleware step shared one mutable request: an
alternative that changed the JSON body and then raised left its partial
changes for the next alternative. The handler now copies the body
before each step and restores it, in place, after each failed
alternative, so every alternative starts from the body as it was before
the step.

The middleware interface is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Take the snapshot of the body only for steps with more than one
alternative, and skip the restore after the last one. The docs say
that only the JSON body is restored, not other request state or a
replaced body.

Refs #313

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

sourcery-ai Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Middleware alternatives now receive an isolated JSON body state: the handler snapshots object bodies for multi-alternative steps and restores mutations in place after each failed non-final attempt, while documentation and tests define and verify the supported scope.

Sequence diagram for restoring middleware request bodies

sequenceDiagram
    participant Handler as MiddlewareHandler
    participant Request as flask.Request
    participant Alternative as Middleware alternative

    Handler->>Request: deepcopy(request.json)
    loop Alternatives in middleware step
        Handler->>Alternative: apply(request)
        alt middleware succeeds
            Alternative-->>Handler: return
        else middleware fails and another alternative remains
            Alternative-->>Handler: raise exception
            Handler->>Handler: _restore_body(request, snapshot)
            Handler->>Request: clear body and update snapshot
        else final middleware fails
            Alternative-->>Handler: raise exception
            Handler-->>Handler: raise MiddlewareException
        end
    end
Loading

Flow diagram for middleware alternative body restoration

flowchart TD
    A[Start middleware step] --> B{More than one alternative?}
    B -- Yes --> C[Snapshot request.json]
    B -- No --> D[No snapshot]
    C --> E[Try middleware alternative]
    D --> E
    E --> F{Applied successfully?}
    F -- Yes --> G[Continue to next step]
    F -- No, another alternative --> H[_restore_body]
    H --> I[Try next alternative]
    I --> F
    F -- No, final alternative --> J[Raise MiddlewareException]
Loading

File-Level Changes

Change Details Files
Restore in-place JSON body mutations between failed middleware alternatives.
  • Deep-copy the body only for steps with multiple alternatives.
  • Restore dictionary contents after each failed alternative that has a successor, preserving the original object in place.
  • Leave the final failure behavior unchanged by raising when all alternatives fail.
pro_tes/middleware/middleware_handler.py
Clarify the restoration behavior and its limitations.
  • Document that only in-place request.json changes are reverted.
  • Explicitly exclude headers, environment, request attributes, and replaced or non-object bodies from restoration.
docs/middlewares.md
pro_tes/middleware/middleware_handler.py
Add regression coverage for alternative isolation and restoration scope.
  • Test consecutive failing alternatives and nested body mutations.
  • Test that non-object JSON bodies remain unchanged and existing fallback behavior still works.
tests/middleware/test_middleware_handler.py

Assessment against linked issues

Issue Objective Addressed Explanation
#313 Restore the JSON body to its state before a middleware step whenever an alternative fails, so subsequent alternatives do not inherit that failed alternative’s in-place changes. ✅
#313 Add regression coverage showing consecutive failing alternatives cannot leak body changes to a successful alternative, including relevant body shapes. ✅
#313 Document the behavior and scope of restoration for middleware authors. ✅

Possibly linked issues


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

@read-the-docs-community

read-the-docs-community Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Documentation build overview

📚 proTES | 🛠️ Build #35384931 | 📁 Comparing ea80fbe against latest (0770405)

  🔍 Preview build  

2 files changed
± middlewares/index.html
± reference/index.html

@uniqueg
uniqueg marked this pull request as ready for review October 24, 2026 23:06
@codecov

codecov Bot commented Oct 24, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (5a15b5e) to head (ea80fbe).
⚠️ Report is 1 commits behind head on dev.

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #318   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           29        29           
  Lines         2469      2479   +10     
=========================================
+ Hits          2469      2479   +10     

☔ 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.

@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 reviewed your changes and they look great!

Sourcery assessment

Approved.


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

@uniqueg
uniqueg merged commit ec9a510 into dev Oct 24, 2026
17 checks passed
@uniqueg
uniqueg deleted the fix/middleware-alternatives branch October 24, 2026 23:15
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.

fix: undo changes of failed middlewares

1 participant