Skip to content

Conversation

@hiteshghuge
Copy link
Collaborator

@hiteshghuge hiteshghuge commented Jun 13, 2025

Summary by CodeRabbit

  • Chores
    • Updated database indexing strategy to improve performance and efficiency. No changes to user-facing features or functionality.

@coderabbitai
Copy link

coderabbitai bot commented Jun 13, 2025

Walkthrough

The changes update the MongoDB index definitions in the _ensure_indices method of the KMongoTrackerStore class. Several indexes are removed and replaced with a new compound index, and the field order in another compound index is modified. No public interfaces or control flow are affected.

Changes

File(s) Change Summary
kairon/shared/trackers.py Revised MongoDB index definitions: removed several indexes, added a new compound index, and changed the field order in an existing compound index within the _ensure_indices method.

Sequence Diagram(s)

sequenceDiagram
    participant App
    participant KMongoTrackerStore
    participant MongoDB

    App->>KMongoTrackerStore: Initialize or update tracker store
    KMongoTrackerStore->>MongoDB: Ensure new set of indexes on conversations collection
    MongoDB-->>KMongoTrackerStore: Indexes created/updated as per new definitions
Loading

Possibly related PRs

  • - created index for tracker #1999: Also modifies the MongoDB indexes in the _ensure_indices method of the KMongoTrackerStore class, directly involving the same logic and method.

Suggested reviewers

  • sfahad1414
  • sushantpatade

Poem

In the warren where data hops and flows,
Indexes shift as the query wind blows.
Old paths are cleared, new trails appear,
Compound and tidy, the searches steer.
With whiskers twitching, I watch the store—
Fast and efficient, now more than before!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
kairon/shared/trackers.py (1)

70-70: Field-order change may improve current queries but hurts equality look-ups

Placing event.timestamp before event.event means queries that filter on event.event (exact match) but do not constrain the timestamp will now have to scan the whole timestamp range. If any analytics path relies on event.event = "session_started" without a timestamp predicate, the previous order was more selective.

Double-check typical patterns; if both exist you might need two separate compound indexes rather than re-ordering one.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f6ef617 and 19e727f.

📒 Files selected for processing (1)
  • kairon/shared/trackers.py (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Codacy Static Code Analysis
  • GitHub Check: Python CI
  • GitHub Check: Analyze (python)
🔇 Additional comments (1)
kairon/shared/trackers.py (1)

68-68: Asc/Desc switch – verify query plans

Changing event.timestamp from DESCENDING to ASCENDING aligns with the $sort : {"event.timestamp" : 1} used later, so looks correct.
However, confirm there are no dashboards / cron jobs that still request sort({"event.timestamp": -1}); they will no longer be covered.

Comment on lines 64 to 71
def _ensure_indices(self) -> None:
indexes = [
IndexModel([("sender_id", ASCENDING), ("event.event", ASCENDING)]),
IndexModel([("type", ASCENDING), ("timestamp", ASCENDING)]),
IndexModel([("sender_id", ASCENDING), ("conversation_id", ASCENDING)]),
IndexModel([("event.event", ASCENDING), ("event.timestamp", DESCENDING)]),
IndexModel([("event.name", ASCENDING), ("event.timestamp", DESCENDING)]),
IndexModel([("event.timestamp", DESCENDING)]),
IndexModel([("event.timestamp", ASCENDING), ("event.event", ASCENDING)]),
IndexModel([("sender_id", ASCENDING), ("type", ASCENDING), ("event.event", ASCENDING)]),
IndexModel([("sender_id", ASCENDING), ("type", ASCENDING), ("event.event", ASCENDING), ("event.timestamp", ASCENDING)]),
IndexModel([("sender_id", ASCENDING), ("type", ASCENDING), ("event.timestamp", ASCENDING), ("event.event", ASCENDING)]),
]
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Potential index bloat & missing maintenance hooks

The new compound indexes are created un-named and without first removing the obsolete ones that existed in production (type+timestamp, event.event+timestamp, etc.).
Because MongoDB treats [(a,1),(b,1)] and [(a,1),(b,-1)] and different field orders as distinct, create_indexes() will happily add the new keys and keep the old ones. On a busy conversations collection this can:

• double the on-disk index size and memory footprint
• slow down writes while the extra indexes are being built
• leave the optimiser with too many similar choices

I strongly recommend:

-indexes = [
-    IndexModel([("sender_id", ASCENDING), ("event.event", ASCENDING)]),
-    ...
-    IndexModel([("event.timestamp", ASCENDING), ("event.event", ASCENDING)]),
-    ...
-]
+# obsolete = [
+#     ("type_1_timestamp_-1",            True),
+#     ("event.event_1_event.timestamp_-1", True),
+#     ("event.name_1_event.timestamp_-1", True),
+# ]
+# for name, drop in obsolete:
+#     if drop and name in self.conversations.index_information():
+#         self.conversations.drop_index(name)
+
+indexes = [
+    IndexModel([("sender_id", ASCENDING), ("event.event", ASCENDING)],
+               name="sender_event_idx", background=True),
+    IndexModel([("sender_id", ASCENDING), ("conversation_id", ASCENDING)],
+               name="sender_cid_idx",    background=True),
+    IndexModel([("event.timestamp", ASCENDING), ("event.event", ASCENDING)],
+               name="ts_event_idx",      background=True),
+    IndexModel([("sender_id", ASCENDING), ("type", ASCENDING), ("event.timestamp", ASCENDING), ("event.event", ASCENDING)],
+               name="sender_type_ts_evt_idx", background=True),
+]

• Give every index an explicit name so future migrations can be idempotent and easy to drop.
• Build them with background=True (or {"background":True} on legacy servers) to avoid blocking writes.
• Drop the superseded keys inside _ensure_indices() – it already runs at start-up when only one process owns the connection, so it’s safe.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def _ensure_indices(self) -> None:
indexes = [
IndexModel([("sender_id", ASCENDING), ("event.event", ASCENDING)]),
IndexModel([("type", ASCENDING), ("timestamp", ASCENDING)]),
IndexModel([("sender_id", ASCENDING), ("conversation_id", ASCENDING)]),
IndexModel([("event.event", ASCENDING), ("event.timestamp", DESCENDING)]),
IndexModel([("event.name", ASCENDING), ("event.timestamp", DESCENDING)]),
IndexModel([("event.timestamp", DESCENDING)]),
IndexModel([("event.timestamp", ASCENDING), ("event.event", ASCENDING)]),
IndexModel([("sender_id", ASCENDING), ("type", ASCENDING), ("event.event", ASCENDING)]),
IndexModel([("sender_id", ASCENDING), ("type", ASCENDING), ("event.event", ASCENDING), ("event.timestamp", ASCENDING)]),
IndexModel([("sender_id", ASCENDING), ("type", ASCENDING), ("event.timestamp", ASCENDING), ("event.event", ASCENDING)]),
]
def _ensure_indices(self) -> None:
# drop any obsolete indexes before creating the new ones
obsolete = [
("type_1_timestamp_-1", True),
("event.event_1_event.timestamp_-1", True),
("event.name_1_event.timestamp_-1", True),
]
for name, drop in obsolete:
if drop and name in self.conversations.index_information():
self.conversations.drop_index(name)
indexes = [
IndexModel(
[("sender_id", ASCENDING), ("event.event", ASCENDING)],
name="sender_event_idx",
background=True,
),
IndexModel(
[("sender_id", ASCENDING), ("conversation_id", ASCENDING)],
name="sender_cid_idx",
background=True,
),
IndexModel(
[("event.timestamp", ASCENDING), ("event.event", ASCENDING)],
name="ts_event_idx",
background=True,
),
IndexModel(
[
("sender_id", ASCENDING),
("type", ASCENDING),
("event.timestamp", ASCENDING),
("event.event", ASCENDING),
],
name="sender_type_ts_evt_idx",
background=True,
),
]
# … rest of _ensure_indices, e.g.:
# self.conversations.create_indexes(indexes)
🤖 Prompt for AI Agents
In kairon/shared/trackers.py around lines 64 to 71, the compound indexes are
created without explicit names and without removing obsolete indexes, which can
cause index bloat and performance issues. To fix this, assign explicit unique
names to each IndexModel, set background=True to avoid blocking writes during
index creation, and add logic in _ensure_indices() to drop any superseded or
obsolete indexes before creating the new ones, ensuring the process is
idempotent and safe during startup.

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.

2 participants