Skip to content

fix(api): make tenant deletion cleanup atomic - #12379

Merged
AdriiiPRodri merged 1 commit into
masterfrom
branch-fix-tenant-deletion-transaction
Aug 6, 2026
Merged

AdriiiPRodri merged 1 commit into
masterfrom
branch-fix-tenant-deletion-transaction

Conversation

@AdriiiPRodri

@AdriiiPRodri AdriiiPRodri commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Context

Tenant deletion opened transaction.atomic() on the default database connection while membership and user writes were routed through admin_db. A failure during user cleanup could therefore leave memberships partially deleted.

This was reproduced on the latest OSS master with separate default and admin database connections. Cloud has a dedicated implementation, so this PR must not be synchronized automatically.

Description

  • Bind the tenant deletion transaction to MainRouter.admin_db.
  • Add a multi-database regression test that verifies membership deletion rolls back when exclusive-user cleanup fails.
  • Add an API changelog fragment.
  • Apply the skip-sync label because Cloud has a separate tailored PR.

Steps to review

  1. Run the relevant API tests:

    cd api
    uv run pytest -q src/backend/api/tests/test_views.py::TestTenantDeletionTransactions src/backend/api/tests/test_views.py::TestTenantViewSet src/backend/tasks/tests/test_deletion.py::TestDeleteTenant

    Expected result: 54 passed.

  2. Run the API formatting and lint checks:

    uv run ruff format --check src/backend
    uv run ruff check src/backend

Checklist

Community Checklist
  • This feature/issue is listed in the open issues or roadmap.prowler.com
  • It is assigned to me
  • I reviewed the open pull requests and found no duplicate implementation
  • The change is covered by tests.
  • No additional code documentation is required.
  • Backport requirements were reviewed.
  • No README change is required.

SDK/CLI

  • Are there new checks included in this PR? No

API

  • Tenant deletion behavior works as expected.
  • Endpoint response output: Not changed.
  • EXPLAIN ANALYZE: Not applicable, no query shape or index change.
  • Performance test results: Not applicable.
  • API specs do not need regeneration.
  • No version update is required.
  • An API changelog fragment is included.

License

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

Summary by CodeRabbit

  • Bug Fixes
    • Improved tenant deletion reliability by ensuring membership records are preserved when exclusive-user cleanup fails.
    • Prevented asynchronous deletion tasks from being scheduled after an unsuccessful deletion attempt.
  • Tests
    • Added coverage for transactional tenant deletion and cleanup failures.
  • Documentation
    • Added a changelog entry describing the tenant deletion fix.

@coderabbitai

coderabbitai Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Tenant deletion cleanup now runs in an atomic transaction on the admin database. A regression test verifies membership rollback, exception propagation, and prevention of asynchronous cleanup when user deletion fails. A changelog entry documents the behavior.

Changes

Tenant deletion transaction

Layer / File(s) Summary
Admin-database transaction routing
api/src/backend/api/v1/views.py, api/changelog.d/tenant-deletion-transaction.fixed.md
Tenant deletion cleanup now uses an atomic transaction on MainRouter.admin_db. The changelog records the transactional behavior.
Rollback failure validation
api/src/backend/api/tests/test_views.py
The test injects a failing User deletion signal, verifies the exception and membership rollback, and confirms that no asynchronous cleanup task is scheduled.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

Suggested reviewers: josema-xyz

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the primary change: making tenant deletion cleanup atomic.
Description check ✅ Passed The description covers context, implementation, review steps, testing, checklist items, API impact, and the changelog.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch branch-fix-tenant-deletion-transaction

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

✅ All required changelog fragments are present.

@github-actions

github-actions Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

No Conflicts

No conflict markers, and the branch merges cleanly into its base.

@AdriiiPRodri
AdriiiPRodri marked this pull request as ready for review August 6, 2026 14:58
@AdriiiPRodri
AdriiiPRodri requested a review from a team August 6, 2026 14:58
@AdriiiPRodri
AdriiiPRodri marked this pull request as draft August 6, 2026 14:59
@AdriiiPRodri
AdriiiPRodri marked this pull request as ready for review August 6, 2026 14:59
@AdriiiPRodri
AdriiiPRodri requested a review from Copilot August 6, 2026 15:00

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@api/src/backend/api/v1/views.py`:
- Line 1445: Update destroy() to register delete_tenant_task with
transaction.on_commit using MainRouter.admin_db after the tenant cleanup writes,
rather than launching it immediately. Ensure the callback is registered within
the relevant atomic flow so the task starts only after the outer admin
transaction commits.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: 6130d580-2c75-4334-b0b7-36e8bdaaa5e8

📥 Commits

Reviewing files that changed from the base of the PR and between e2cae35 and 95a736c.

📒 Files selected for processing (3)
  • api/changelog.d/tenant-deletion-transaction.fixed.md
  • api/src/backend/api/tests/test_views.py
  • api/src/backend/api/v1/views.py

Comment thread api/src/backend/api/v1/views.py
@github-actions

github-actions Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

🔒 Container Security Scan

Image: prowler-api:df7bea8
Last scan: 2026-08-06 15:03:39 UTC

✅ No Vulnerabilities Detected

The container image passed all security checks. No known CVEs were found.

📋 Resources:

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 fixes a multi-DB transactional consistency issue in the API tenant deletion flow by ensuring the cleanup transaction is executed on the same database alias (MainRouter.admin_db) used for membership/user deletion, and adds a regression test to prevent partial cleanup on failure.

Changes:

  • Bind TenantViewSet.destroy() cleanup to transaction.atomic(using=MainRouter.admin_db) to ensure rollback applies to admin-routed writes.
  • Add a multi-database regression test that simulates a user deletion failure via pre_delete and asserts membership deletion is rolled back and no async deletion task is scheduled.
  • Add an API changelog fragment documenting the fix.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated no comments.

File Description
api/src/backend/api/v1/views.py Runs tenant deletion cleanup inside an atomic transaction on MainRouter.admin_db to make membership/user cleanup rollback correctly.
api/src/backend/api/tests/test_views.py Adds a regression test covering rollback behavior when exclusive-user cleanup fails under separate DB connections.
api/changelog.d/tenant-deletion-transaction.fixed.md Documents the tenant deletion transactional fix as a changelog fragment.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@codecov

codecov Bot commented Aug 6, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94.55%. Comparing base (d8c8027) to head (95a736c).
⚠️ Report is 1 commits behind head on master.

Additional details and impacted files
@@           Coverage Diff           @@
##           master   #12379   +/-   ##
=======================================
  Coverage   94.55%   94.55%           
=======================================
  Files         271      271           
  Lines       42191    42211   +20     
=======================================
+ Hits        39894    39914   +20     
  Misses       2297     2297           
Flag Coverage Δ
api 94.55% <100.00%> (+<0.01%) ⬆️

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

Components Coverage Δ
prowler ∅ <ø> (∅)
api 94.55% <100.00%> (+<0.01%) ⬆️
mcp_server ∅ <ø> (∅)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@github-actions

github-actions Bot commented Aug 6, 2026

Copy link
Copy Markdown
Contributor

🔎 Container Security Scan (Grype)

Image: prowler-api:df7bea8
Last scan: 2026-08-06 15:05:35 UTC

✅ Nothing Blocking

No findings at critical or high severity.

Not blocking at this cutoff — medium: 19, low: 4, negligible: 1.

44 finding(s) excluded by .grype.yaml, each with a documented reason.


📋 Resources:

@AdriiiPRodri
AdriiiPRodri merged commit cf558c5 into master Aug 6, 2026
53 of 57 checks passed
@AdriiiPRodri
AdriiiPRodri deleted the branch-fix-tenant-deletion-transaction branch August 6, 2026 15:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants