Skip to content

chore(perf): optimize model aggregation pipelines and remove dead ones - #41157

Draft
KevLehman wants to merge 5 commits into
developfrom
chore/model-aggregations-perf
Draft

chore(perf): optimize model aggregation pipelines and remove dead ones#41157
KevLehman wants to merge 5 commits into
developfrom
chore/model-aggregations-perf

Conversation

@KevLehman

@KevLehman KevLehman commented Jul 3, 2026

Copy link
Copy Markdown
Member

Proposed changes (including videos or screenshots)

Audit of every .aggregate() in packages/models + EE raw models, applying only rewrites that return byte-identical output (verified doc-by-doc against seeded data).

Pipeline rewrites

  • LivechatRooms.getAnalyticsBetweenDate / getAnalyticsMetricsBetweenDateWithMessages: message counting moved into the $lookup sub-pipeline ($count) instead of exploding every joined message through $unwind+$group. The historical msgs: 1 for zero-message rooms is preserved.
  • Messages.findAllNumberOfTransferredRooms: transfer messages grouped by rid before the room $lookup — one join per distinct room projecting only departmentId, department filter inside the sub-pipeline.
  • Rooms.getSubscribedRoomIdsWithoutE2EKeys: subscription filter (u._id, E2EKey) inside the $lookup + $limit 1. Availability fix: the old shape materializes the full room membership as one array per room doc, so very large encrypted rooms can overflow the 16MB BSON limit and error.
  • Sessions: logintAtloginAt index typo fix. (A $$ROOT-trim of the hourly engagement pipelines was measured as a consistent ~5% regression and reverted — see benchmark notes.)
  • LivechatInquiry: {status} index widened to {status, department} (prefix keeps serving status-only queries).

Dead code removed (only model + typing references existed): LivechatRooms.findAllNumberOfTransferredRooms (runtime uses the Messages variant), Rooms.findChannelsByTypesWithNumberOfMessagesBetweenDate + builder, Messages.findOneByFederationIdAndUsernameOnReactions, Sessions.getActiveUsersBetweenDates, LivechatDepartmentAgents.findAgentsByAgentIdAndBusinessHourId (CE + EE files, class went empty). Net −400 lines.

Benchmarks — k6 at 8 req/s for 60s per build (develop vs branch, same seeded data) + explain('executionStats') on old vs new pipelines. MongoDB 7.0.16. Dataset: 2.2k livechat rooms / 146k messages / 60k queued inquiries / 118k subscriptions. Every rewritten pipeline verified to return identical output before measuring.

k6, endpoint level (median / p95):

Endpoint develop branch
livechat/analytics/dashboards/conversation-totalizers (30d) 464.7 / 482.5ms 285.2 / 326.3ms (−39% median)
livechat/analytics/dashboards/charts/chats 28.2 / 42.0ms 30.1 / 34.5ms (flat — small date slices)
engagement-dashboard sessions charts ×2 ~11 / 25–43ms ~13 / 16ms (flat — pipeline change reverted, typo fix only)

explain, engine level:

Aggregation old new
queue worker getDistinctQueuedDepartments (60k queued) 27ms · 120,000 docs examined 1ms · 0 docs / 34 keys (covered DISTINCT_SCAN)
getAnalyticsBetweenDate (146k msgs) 387ms 219ms (1.77x; same keys examined — gain is dropping the $unwind+$group)
transferred-chats pipeline (7.4k transfer msgs) 231.7ms 72.8ms (3.18x)
E2E getSubscribedRoomIdsWithoutE2EKeys (50 rooms ×2,000 subs) 13ms 15ms — kept for memory: old shape loads the full membership as one array per room (~0.5–1KB/sub), breaking E2EE key reset around 15–20k members on the 16MB BSON limit

Changes that measured neutral-or-worse were reverted rather than shipped (Sessions $$ROOT trim: real ~5% regression; Users pipeline micro-cleanups and allowDiskUse flags: no measurable gain).

Issue(s)

Steps to test or reproduce

  • Omnichannel analytics dashboards (conversation totalizers, charts) return the same numbers as develop.
  • EE departments analytics → total transferred chats: same values, with and without department filter.
  • Engagement dashboard → users by time of day / busiest chat times unchanged.
  • E2EE: reset E2EE keys, encrypted rooms still prompt for key redistribution.
  • Livechat queue keeps dispatching per-department queues (incl. inquiries without department).

Further comments

Every rewrite was validated for output-equivalence before benchmarking; regressions found during benchmarking (e.g. sub-pipeline lookups losing the SBE hash-join) are documented and were only kept where they fix a failure mode (the 16MB BSON doc limit on the E2E lookup) rather than latency.

An earlier revision added allowDiskUse: true to a few pipelines; those flags were dropped — Rocket.Chat requires MongoDB >=7.0, where allowDiskUseByDefault: true (since 6.0) spills memory-exceeding stages to disk automatically, making them no-ops on supported deployments.

Review in cubic

Summary by CodeRabbit

  • Performance Improvements

    • Dashboard and chart loading should be faster for workspaces with large message and session volumes.
    • Encrypted room key distribution is faster after a user resets end-to-end encryption keys.
  • Bug Fixes

    • Improved livechat analytics and session reporting performance.
    • Fixed several backend queries and indexes to make large-data reports more reliable and efficient.

- LivechatRooms.getAnalyticsBetweenDate/getAnalyticsMetricsBetweenDateWithMessages:
  count messages inside the $lookup sub-pipeline instead of $unwind+$group
  (conversation-totalizers -39% median; preserves msgs:1 for zero-message rooms)
- Messages.findAllNumberOfTransferredRooms: group by rid before the room $lookup,
  one join per distinct room projecting only departmentId (3.18x)
- LivechatInquiry: widen {status} index to {status, department} so
  getDistinctQueuedDepartments becomes a covered scan (120k -> 0 docs examined
  per queue-worker cycle); allowDiskUse on getCurrentSortedQueueAsync
- Rooms.getSubscribedRoomIdsWithoutE2EKeys: filter subscriptions inside the
  $lookup, avoiding full-membership arrays that can overflow the 16MB doc limit
- Sessions: trim session:'$$ROOT' to used fields in hourly engagement pipelines,
  add allowDiskUse, fix logintAt index typo
- Users: drop redundant second $group in getTotalOfRegisteredUsersByDate;
  replace $unwind+$group regroup with $project+$map in findAgentsWithDepartments
- Remove dead methods: LivechatRooms.findAllNumberOfTransferredRooms,
  Rooms.findChannelsByTypesWithNumberOfMessagesBetweenDate (+builder),
  Messages.findOneByFederationIdAndUsernameOnReactions,
  Sessions.getActiveUsersBetweenDates,
  LivechatDepartmentAgents.findAgentsByAgentIdAndBusinessHourId (CE+EE files)

All rewritten pipelines verified to return identical output against seeded data.
@KevLehman
KevLehman requested a review from a team as a code owner July 3, 2026 01:36
@dionisio-bot

dionisio-bot Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is missing the 'stat: QA assured' label
  • This PR is missing the required milestone or project

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@changeset-bot

changeset-bot Bot commented Jul 3, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 6630944

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 5 packages
Name Type
@rocket.chat/meteor Patch
@rocket.chat/models Patch
@rocket.chat/model-typings Patch
@rocket.chat/core-typings Patch
@rocket.chat/rest-typings Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai

coderabbitai Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

This PR removes unused livechat model APIs and rewrites several MongoDB aggregation pipelines and indexes across livechat, messages, rooms, sessions, and users. It also adds a changeset for patch releases and performance notes.

Changes

Performance refactors and dead code removal

Layer / File(s) Summary
Remove unused livechat and model APIs
apps/meteor/ee/server/models/*, packages/models/src/models/LivechatDepartmentAgents.ts, packages/model-typings/src/models/*
Removes the LivechatDepartmentAgents registration and implementation, plus unused method declarations for transferred rooms, channel-message counts, federation reactions lookup, and active users between dates.
Rewrite livechat analytics lookups
packages/models/src/models/LivechatRooms.ts, packages/models/src/models/LivechatInquiry.ts
Reworks the livechat analytics message lookups to count within the lookup pipeline, and adds department to the LivechatInquiry compound index.
Refactor transferred-room aggregation
packages/models/src/models/Messages.ts
Changes transferred-room counting to aggregate per room first, then resolve room documents with an optional department filter.
Update room, session, and user aggregations
packages/models/src/models/Rooms.ts, packages/models/src/models/Sessions.ts, packages/models/src/models/Users.ts
Refactors the E2EE subscription lookup, removes channel-message analytics helpers, corrects the session index key, narrows session aggregation projections, and simplifies user aggregation pipelines.
Update performance changeset
.changeset/model-aggregations-perf.md
Adds patch bumps and performance notes for the affected packages.

Estimated code review effort: 4 (Complex) | ~60 minutes

Suggested labels: type: chore

Suggested reviewers: ricardogarim, sampaiodiego

🚥 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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: performance-focused aggregation pipeline optimizations plus removal of dead model methods.

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.

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

🧹 Nitpick comments (1)
packages/models/src/models/LivechatRooms.ts (1)

2076-2076: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Remove the new implementation comments.

These comments explain expected legacy behavior, but the project guideline asks to avoid implementation comments; consider encoding this expectation in tests instead. As per coding guidelines, "Avoid code comments in the implementation".

Also applies to: 2133-2133

🤖 Prompt for 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.

In `@packages/models/src/models/LivechatRooms.ts` at line 2076, Remove the
implementation comments from LivechatRooms and related logic, including the note
in the rooms aggregation flow and the matching comment near the other referenced
location. Keep the behavior unchanged in the relevant methods or query helpers,
and if the legacy msgs: 1 expectation needs to be preserved, capture it in tests
instead of inline comments. Use the surrounding LivechatRooms aggregation code
to locate the commented sections and delete only the comments, not the logic.

Source: Coding guidelines

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

Nitpick comments:
In `@packages/models/src/models/LivechatRooms.ts`:
- Line 2076: Remove the implementation comments from LivechatRooms and related
logic, including the note in the rooms aggregation flow and the matching comment
near the other referenced location. Keep the behavior unchanged in the relevant
methods or query helpers, and if the legacy msgs: 1 expectation needs to be
preserved, capture it in tests instead of inline comments. Use the surrounding
LivechatRooms aggregation code to locate the commented sections and delete only
the comments, not the logic.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 15a2cee0-bdc2-4247-b147-e7ef24c315e7

📥 Commits

Reviewing files that changed from the base of the PR and between c7aff48 and 957015e.

📒 Files selected for processing (16)
  • .changeset/model-aggregations-perf.md
  • apps/meteor/ee/server/models/LivechatDepartmentAgents.ts
  • apps/meteor/ee/server/models/raw/LivechatDepartmentAgents.ts
  • apps/meteor/ee/server/models/startup.ts
  • packages/model-typings/src/models/ILivechatDepartmentAgentsModel.ts
  • packages/model-typings/src/models/ILivechatRoomsModel.ts
  • packages/model-typings/src/models/IMessagesModel.ts
  • packages/model-typings/src/models/IRoomsModel.ts
  • packages/model-typings/src/models/ISessionsModel.ts
  • packages/models/src/models/LivechatDepartmentAgents.ts
  • packages/models/src/models/LivechatInquiry.ts
  • packages/models/src/models/LivechatRooms.ts
  • packages/models/src/models/Messages.ts
  • packages/models/src/models/Rooms.ts
  • packages/models/src/models/Sessions.ts
  • packages/models/src/models/Users.ts
💤 Files with no reviewable changes (9)
  • packages/model-typings/src/models/ILivechatRoomsModel.ts
  • packages/model-typings/src/models/IMessagesModel.ts
  • packages/model-typings/src/models/ILivechatDepartmentAgentsModel.ts
  • packages/models/src/models/LivechatDepartmentAgents.ts
  • apps/meteor/ee/server/models/LivechatDepartmentAgents.ts
  • apps/meteor/ee/server/models/raw/LivechatDepartmentAgents.ts
  • packages/model-typings/src/models/ISessionsModel.ts
  • packages/model-typings/src/models/IRoomsModel.ts
  • apps/meteor/ee/server/models/startup.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (5)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Hacktron Security Check
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • packages/models/src/models/LivechatInquiry.ts
  • packages/models/src/models/Sessions.ts
  • packages/models/src/models/Users.ts
  • packages/models/src/models/Messages.ts
  • packages/models/src/models/Rooms.ts
  • packages/models/src/models/LivechatRooms.ts
🧠 Learnings (4)
📚 Learning: 2026-03-16T21:50:37.589Z
Learnt from: amitb0ra
Repo: RocketChat/Rocket.Chat PR: 39676
File: .changeset/migrate-users-register-openapi.md:3-3
Timestamp: 2026-03-16T21:50:37.589Z
Learning: For changes related to OpenAPI migrations in Rocket.Chat/OpenAPI, when removing endpoint types and validators from rocket.chat/rest-typings (e.g., UserRegisterParamsPOST, /v1/users.register) document this as a minor changeset (not breaking) per RocketChat/Rocket.Chat-Open-API#150 Rule 7. Note that the endpoint type is re-exposed via a module augmentation .d.ts in the consuming package (e.g., packages/web-ui-registration/src/users-register.d.ts). In reviews, ensure the changeset clearly states: this is a non-breaking change, the major version should not be bumped, and the changeset reflects a minor version bump. Do not treat this as a breaking change during OpenAPI migrations.

Applied to files:

  • .changeset/model-aggregations-perf.md
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.

Applied to files:

  • packages/models/src/models/LivechatInquiry.ts
  • packages/models/src/models/Sessions.ts
  • packages/models/src/models/Users.ts
  • packages/models/src/models/Messages.ts
  • packages/models/src/models/Rooms.ts
  • packages/models/src/models/LivechatRooms.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.

Applied to files:

  • packages/models/src/models/LivechatInquiry.ts
  • packages/models/src/models/Sessions.ts
  • packages/models/src/models/Users.ts
  • packages/models/src/models/Messages.ts
  • packages/models/src/models/Rooms.ts
  • packages/models/src/models/LivechatRooms.ts
📚 Learning: 2026-05-06T12:21:44.083Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 40256
File: apps/meteor/client/components/CreateDiscussion/CreateDiscussion.tsx:121-149
Timestamp: 2026-05-06T12:21:44.083Z
Learning: Field wrappers in rocket.chat/fuselage-forms (Field, FieldLabel, FieldRow, FieldError, FieldHint) auto-create htmlFor/id associations, aria-describedby, and role="alert" for errors. Do not manually set htmlFor, id, aria-describedby, or role attributes when using these wrappers. This automatic wiring does not apply to plain rocket.chat/fuselage components, which require explicit ID wiring per the accessibility docs. In code reviews, prefer using fuselage-forms wrappers for form fields and verify there is no unnecessary manual ID/aria wiring in files that use these wrappers. If a component uses plain fuselage components, ensure proper id wiring as per docs.

Applied to files:

  • packages/models/src/models/LivechatInquiry.ts
  • packages/models/src/models/Sessions.ts
  • packages/models/src/models/Users.ts
  • packages/models/src/models/Messages.ts
  • packages/models/src/models/Rooms.ts
  • packages/models/src/models/LivechatRooms.ts
🔇 Additional comments (8)
packages/models/src/models/LivechatRooms.ts (1)

2045-2045: LGTM!

Also applies to: 2063-2075, 2077-2077, 2102-2102, 2119-2132, 2134-2134

packages/models/src/models/LivechatInquiry.ts (1)

66-66: LGTM!

Also applies to: 285-290

packages/models/src/models/Messages.ts (2)

195-216: LGTM!

Also applies to: 563-564


225-230: 🎯 Functional Correctness

No change needed for unscoped counts. The null department bucket is intentional when no departmentId is passed, so the room.0 filter should stay inside the department-specific branch.

			> Likely an incorrect or invalid review comment.
packages/models/src/models/Rooms.ts (1)

12-12: LGTM!

Also applies to: 1996-2013

packages/models/src/models/Sessions.ts (1)

990-990: LGTM!

Also applies to: 1105-1105, 1128-1128, 1196-1203, 1237-1237

packages/models/src/models/Users.ts (1)

275-288: LGTM!

Also applies to: 1043-1045

.changeset/model-aggregations-perf.md (1)

1-7: LGTM!

@cubic-dev-ai cubic-dev-ai 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.

1 issue found across 16 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="packages/models/src/models/Users.ts">

<violation number="1" location="packages/models/src/models/Users.ts:282">
P2: Agents without department assignments now return a different `departments` shape (`[]` instead of previous `[null]`), which changes the omnichannel users response for that edge case. If output compatibility is required, preserve the empty-lookup case before mapping department IDs.</violation>
</file>

Reply with feedback, questions, or to request a fix.

Re-trigger cubic

Comment thread packages/models/src/models/Users.ts Outdated
Comment on lines 282 to 290
departments: {
$map: {
input: '$departments',
as: 'department',
in: '$$department.departmentId',
},
},
},
},

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.

P2: Agents without department assignments now return a different departments shape ([] instead of previous [null]), which changes the omnichannel users response for that edge case. If output compatibility is required, preserve the empty-lookup case before mapping department IDs.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At packages/models/src/models/Users.ts, line 282:

<comment>Agents without department assignments now return a different `departments` shape (`[]` instead of previous `[null]`), which changes the omnichannel users response for that edge case. If output compatibility is required, preserve the empty-lookup case before mapping department IDs.</comment>

<file context>
@@ -272,21 +272,20 @@ export class UsersRaw extends BaseRaw<IUser, DefaultFields<IUser>> implements IU
+					name: 1,
+					emails: 1,
+					livechat: 1,
+					departments: {
+						$map: {
+							input: '$departments',
</file context>
Suggested change
departments: {
$map: {
input: '$departments',
as: 'department',
in: '$$department.departmentId',
},
},
},
},
departments: {
$cond: [
{ $gt: [{ $size: '$departments' }, 0] },
{
$map: {
input: '$departments',
as: 'department',
in: '$$department.departmentId',
},
},
[null],
],
},

@codecov

codecov Bot commented Jul 3, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 69.21%. Comparing base (6da12d7) to head (6630944).
⚠️ Report is 2 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #41157      +/-   ##
===========================================
- Coverage    69.26%   69.21%   -0.05%     
===========================================
  Files         3536     3536              
  Lines       138592   138598       +6     
  Branches     24681    24720      +39     
===========================================
- Hits         95991    95935      -56     
- Misses       38592    38651      +59     
- Partials      4009     4012       +3     
Flag Coverage Δ
e2e 59.34% <ø> (-0.04%) ⬇️
e2e-api 49.81% <ø> (-0.06%) ⬇️
unit 70.05% <ø> (-0.05%) ⬇️

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

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

KevLehman added 3 commits July 2, 2026 20:23
Rocket.Chat requires MongoDB >=7.0, where allowDiskUseByDefault is true (since
6.0) and memory-exceeding stages spill to disk automatically — the explicit
flags added no behavior on supported deployments.
The trimmed projection measured a consistent ~5% regression (128.5 -> 135.9ms
at 40k sessions, 756 -> 795ms at 200k; non-overlapping ranges) — building the
sub-object per document costs more than the smaller $unwind copies save, and
there is no failure mode to protect against. Only the logintAt -> loginAt
index typo fix remains.

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

🧹 Nitpick comments (2)
packages/models/src/models/Sessions.ts (2)

1191-1198: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Same $$ROOT bloat issue — only day/month/year are used downstream.

The subsequent groups reference only session.day, session.month, and session.year (Lines 1204-1206), yet the entire document is embedded under session and then duplicated by $unwind across the hour range. Narrowing this projection to the actually-used fields would reduce the per-bucket payload size, consistent with this PR's performance goals.

♻️ Suggested fix
 const rangeProject = {
 	$project: {
 		range: {
 			$range: [{ $hour: '$loginAt' }, { $sum: [{ $ifNull: [{ $hour: '$closedAt' }, 23] }, 1] }],
 		},
-		session: '$$ROOT',
+		session: { day: '$day', month: '$month', year: '$year' },
 	},
 };
🤖 Prompt for 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.

In `@packages/models/src/models/Sessions.ts` around lines 1191 - 1198, The
$project in the rangeProject stage is carrying the full $$ROOT document into
session even though downstream only reads session.day, session.month, and
session.year in the groups logic. Update the projection in rangeProject to
include only those needed session fields instead of $$ROOT, so the $unwind over
range does not duplicate unnecessary document data and the pipeline stays lean.

1100-1107: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick win

Avoid $$ROOT before $unwind — project only needed fields.

Setting session: '$$ROOT' embeds the entire session document under session right before $unwind fans it out per range bucket, multiplying the duplicated payload by the bucket count. Since this PR's goal is performance improvement, consider projecting only the specific fields consumed later (if any beyond range), rather than the full document.

♻️ Suggested direction
 const rangeProject = {
 	$project: {
 		range: {
 			$range: [0, 24, groupSize],
 		},
-		session: '$$ROOT',
+		// project only the specific fields needed downstream, e.g.:
+		// loginAt: 1,
 	},
 };
🤖 Prompt for 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.

In `@packages/models/src/models/Sessions.ts` around lines 1100 - 1107, The
`rangeProject` stage in `Sessions` is carrying the full document via `session:
'$$ROOT'` before `$unwind`, which duplicates unnecessary payload across every
bucket. Update the aggregation to project only the fields actually needed in
later stages (or drop `session` entirely if it is unused), keeping the `range`
logic intact while reducing fan-out overhead.
🤖 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.

Nitpick comments:
In `@packages/models/src/models/Sessions.ts`:
- Around line 1191-1198: The $project in the rangeProject stage is carrying the
full $$ROOT document into session even though downstream only reads session.day,
session.month, and session.year in the groups logic. Update the projection in
rangeProject to include only those needed session fields instead of $$ROOT, so
the $unwind over range does not duplicate unnecessary document data and the
pipeline stays lean.
- Around line 1100-1107: The `rangeProject` stage in `Sessions` is carrying the
full document via `session: '$$ROOT'` before `$unwind`, which duplicates
unnecessary payload across every bucket. Update the aggregation to project only
the fields actually needed in later stages (or drop `session` entirely if it is
unused), keeping the `range` logic intact while reducing fan-out overhead.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: fd8aa600-d298-4bc6-b8c9-5d92b71589ba

📥 Commits

Reviewing files that changed from the base of the PR and between ea4101a and 83eba62.

📒 Files selected for processing (1)
  • packages/models/src/models/Sessions.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (4)
  • GitHub Check: ⚙️ Variables Setup
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • packages/models/src/models/Sessions.ts
🧠 Learnings (3)
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.

Applied to files:

  • packages/models/src/models/Sessions.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.

Applied to files:

  • packages/models/src/models/Sessions.ts
📚 Learning: 2026-05-06T12:21:44.083Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 40256
File: apps/meteor/client/components/CreateDiscussion/CreateDiscussion.tsx:121-149
Timestamp: 2026-05-06T12:21:44.083Z
Learning: Field wrappers in rocket.chat/fuselage-forms (Field, FieldLabel, FieldRow, FieldError, FieldHint) auto-create htmlFor/id associations, aria-describedby, and role="alert" for errors. Do not manually set htmlFor, id, aria-describedby, or role attributes when using these wrappers. This automatic wiring does not apply to plain rocket.chat/fuselage components, which require explicit ID wiring per the accessibility docs. In code reviews, prefer using fuselage-forms wrappers for form fields and verify there is no unnecessary manual ID/aria wiring in files that use these wrappers. If a component uses plain fuselage components, ensure proper id wiring as per docs.

Applied to files:

  • packages/models/src/models/Sessions.ts
🔇 Additional comments (1)
packages/models/src/models/Sessions.ts (1)

989-994: LGTM!

The redundant second $group in getTotalOfRegisteredUsersByDate operates on
~#days documents and the findAgentsWithDepartments regroup on a small admin
listing — no measurable perf or memory gain, so they don't belong in this
branch.
@KevLehman KevLehman changed the title perf: optimize model aggregation pipelines and remove dead ones chore(perf): optimize model aggregation pipelines and remove dead ones Jul 3, 2026
@KevLehman
KevLehman marked this pull request as draft July 3, 2026 14:03
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.

1 participant