8000 [PM-21044] - optimize security task ReadByUserIdStatus by jaasen-livefront · Pull Request #5779 · bitwarden/server · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

[PM-21044] - optimize security task ReadByUserIdStatus #5779

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you accoun 8000 t related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 12 commits into
base: main
Choose a base branch
from

Conversation

jaasen-livefront
Copy link
Collaborator
@jaasen-livefront jaasen-livefront commented May 6, 2025

🎟️ Tracking

https://bitwarden.atlassian.net/browse/PM-21044

📔 Objective

The original query What we had was a single flat query with numerous JOINs and a GROUP BY,. This fo 8000 rced the optimizer to consider large intermediate rowsets and perform hidden de‑duping and scans.

PLEASE NOTE - I'm not familiar with db migrations so they're currently absent

After taking @shane-melton's initial plan (see ticket) to use focused CTE's I added further refinements:

Aspect First Draft Final Version
Source tables Used the *View tables (OrganizationUserView, SecurityTaskView, CipherView) plus a join to Organization Switched to the base tables (OrganizationUser, SecurityTask, etc.), avoiding any hidden complexity or overhead that the views might introduce.
Status filter WHERE ST.Status = COALESCE(@Status, ST.Status) → non‑sargable, forced scans/filters Rewritten as WHERE @Status IS NULL OR ST.Status = @Status → fully sargable, pushes directly into an Index Seek on (Status, OrganizationId, CreationDate DESC) and eliminates scan + downstream SORT.
Deduplication UNION in AccessibleCiphers + SELECT DISTINCT in final query (both introduce hidden sorts) Changed to use UNION ALL (no dedupe) and a simple NOT EXISTS semi‑join to exclude duplicates before the append—no Sort or Stream Aggregate needed
EXISTS vs JOIN OR EXISTS (SELECT 1 FROM AccessibleCiphers AC WHERE AC.CipherId = ST.CipherId) (correlated subquery per row) Replaced with a single LEFT JOIN AccessibleCiphers AC ON ST.CipherId = AC.CipherId and WHERE ST.CipherId IS NULL OR AC.CipherId IS NOT NULL. This flattens the plan into one nested‑loops join over the small CTE, cutting I/O and simplifying the optimizer’s job.
Sorting ORDER BY ST.CreationDate DESC always triggered a SORT operator By including CreationDate DESC in the third key of our covering IX_SecurityTask_Status_OrgId_CreationDateDesc index, the engine can return rows in descending order directly—no separate SORT required.
Overall cost ~0.036 (estimated subtree cost) ~0.005 (estimated), 5 ms cold run, 2 logical reads on SecurityTask, no SORT, and only tiny seeks on the CTEs.

Added Four targeted non‑clustered indexes. Eliminated scans on CollectionGroup, SecurityTask, etc., and covered every lookup.

  1. IX_CollectionGroup_GroupId_ReadOnly on (GroupId, ReadOnly)
CREATE NONCLUSTERED INDEX IX_CollectionGroup_GroupId_ReadOnly
  ON dbo.CollectionGroup (GroupId, ReadOnly)
  INCLUDE (CollectionId);
  1. IX_CollectionUser_OrganizationUserId_ReadOnly on (OrganizationUserId, ReadOnly)
CREATE NONCLUSTERED INDEX IX_CollectionUser_OrganizationUserId_ReadOnly
  ON dbo.CollectionUser (OrganizationUserId, ReadOnly)
  INCLUDE (CollectionId);
  1. IX_SecurityTask_Status_OrgId_CreationDateDesc on (Status, OrganizationId, CreationDate DESC) including (CipherId, Type, RevisionDate)
CREATE NONCLUSTERED INDEX IX_SecurityTask_Status_OrgId_CreationDateDesc
  ON dbo.SecurityTask (Status, OrganizationId, CreationDate DESC)
  INCLUDE (CipherId, [Type], RevisionDate);

📸 Screenshots

⏰ Reminders before review

  • Contributor guidelines followed
  • All formatters and local linters executed and passed
  • Written new unit and / or integration tests where applicable
  • Protected functional changes with optionality (feature flags)
  • Used internationalization (i18n) for all UI strings
  • CI builds passed
  • Communicated to DevOps any deployment requirements
  • Updated any necessary documentation (Confluence, contributing docs) or informed the documentation team

🦮 Reviewer guidelines

  • 👍 (:+1:) or similar for great changes
  • 📝 (:memo:) or ℹ️ (:information_source:) for notes or general info
  • ❓ (:question:) for questions
  • 🤔 (:thinking:) or 💭 (:thought_balloon:) for more open inquiry that's not quite a confirmed issue and could potentially benefit from discussion
  • 🎨 (:art:) for suggestions / improvements
  • ❌ (:x:) or ⚠️ (:warning:) for more significant problems or concerns needing attention
  • 🌱 (:seedling:) or ♻️ (:recycle:) for future improvements or indications of technical debt
  • ⛏ (:pick:) for minor or nitpick changes

@jaasen-livefront jaasen-livefront requested a review from a team as a code owner May 6, 2025 21:03
Copy link
codecov bot commented May 6, 2025

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 50.95%. Comparing base (84e5ea1) to head (02e4106).
Report is 15 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #5779      +/-   ##
==========================================
- Coverage   51.01%   50.95%   -0.06%     
==========================================
  Files        1665     1665              
  Lines       75074    75117      +43     
  Branches     6764     6772       +8     
==========================================
- Hits        38299    38276      -23     
- Misses      35252    35322      +70     
+ Partials     1523     1519       -4     

☔ View full report in Codecov by Sentry.
📢 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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@jaasen-livefront jaasen-livefront marked this pull request as draft May 6, 2025 21:09
Copy link
Contributor
github-actions bot commented May 6, 2025

Logo
Checkmarx One – Scan Summary & Detailsa26a6822-7278-4b4a-a55a-8214d506f24f

Great job, no security vulnerabilities found in this Pull Request

@gbubemismith gbubemismith requested a review from a team May 6, 2025 21:16
WHERE
@Status IS NULL
OR ST.Status = @Status
)
SELECT
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The original had a group by which suggested there could be duplicates, do we need a distinct here?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rkac-bw The UNION ALL (no dedupe) and a NOT EXISTS semi‑join will exclude duplicates.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Interesting, the procedure uses UNION ALL between the UserCollectionAccess and filtered GroupCollectionAccess CTEs, which could potentially introduce duplicates. However, the NOT EXISTS subquery in the GroupCollectionAccess CTE and the final left join should make it unique, looks good

FROM UserCollectionAccess AS UA
WHERE UA.CipherId = GC.CipherId
)
)
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After the AccessibleCiphers CTE, you need a comma before defining the SecurityTasks CTE. Without this comma, the query fails?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@rkac-bw Thank you for pointing this out!

@jaasen-livefront jaasen-livefront requested a review from rkac-bw May 8, 2025 23:44
rkac-bw
rkac-bw previously approved these changes Jun 4, 2025
Copy link
Contributor
@rkac-bw rkac-bw left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

lgtm

@jaasen-livefront jaasen-livefront marked this pull request as ready for review June 9, 2025 23:47
@jaasen-livefront jaasen-livefront requested a review from rkac-bw June 9, 2025 23:48
Copy link
Member
@shane-melton shane-melton left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes to the Sproc look good! Just need to make a small change to the migration script.

Added Four targeted non‑clustered indexes. Eliminated scans on CollectionGroup, SecurityTask, etc., and covered every lookup.

I'm not seeing any new indexes being created as mentioned in the PR description?

@jaasen-livefront
Copy link
Collaborator Author

Changes to the Sproc look good! Just need to make a small change to the migration script.

Added Four targeted non‑clustered indexes. Eliminated scans on CollectionGroup, SecurityTask, etc., and covered every lookup.

I'm not seeing any new indexes being created as mentioned in the PR description?

@shane-melton 🤦 It's been so long since I put this together I completely forgot to add them. They're now added.

Copy link

Copy link
Member
@shane-melton shane-melton left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sproc change looks good to me. I'm less familiar with the impacts of the new indexes being created.

@rkac-bw would you mind taking a look at the new nonclustered indexes being added?

@jaasen-livefront
Copy link
Collaborator Author

Sproc change looks good to me. I'm less familiar with the impacts of the new indexes being created.

@rkac-bw would you mind taking a look at the new nonclustered indexes being added?

Indeed they could be overkill. I'm not married to them if you guys prefer to leave them out. ;)

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.

3 participants
0