Skip to content

fix: balance snapshot indexes #2418

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 account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 12, 2025
Merged

fix: balance snapshot indexes #2418

merged 1 commit into from
Mar 12, 2025

Conversation

turip
Copy link
Contributor

@turip turip commented Mar 11, 2025

Overview

This should help with the usage snapshot queries.

Usage snapshot queries are the longest legs in traces. This rework changes the query:

SELECT "balance_snapshots"."id", "balance_snapshots"."namespace", "balance_snapshots"."created_at", "balance_snapshots"."updated_at", "balance_snapshots"."deleted_at", "balance_snapshots"."owner_id", "balance_snapshots"."grant_balances", "balance_snapshots"."usage", "balance_snapshots"."balance", "balance_snapshots"."overage", "balance_snapshots"."at" FROM "balance_snapshots" WHERE (("balance_snapshots"."owner_id" = $1 AND "balance_snapshots"."namespace" = $2) AND "balance_snapshots"."at" <= $3) AND "balance_snapshots"."deleted_at" IS NULL ORDER BY "balance_snapshots"."at" DESC, "balance_snapshots"."updated_at" DESC LIMIT 1

Plan before the index:

                             QUERY PLAN
-----------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=8.32..8.32 rows=1 width=196)
   ->  Sort  (cost=8.32..8.32 rows=1 width=196)
         Sort Key: at DESC, updated_at DESC
         ->  Index Scan Backward using balancesnapshot_namespace_at on balance_snapshots  (cost=0.28..8.31 rows=1 width=196)
               Index Cond: (((namespace)::text = 'org_test'::text) AND (at <= now()))
               Filter: ((deleted_at IS NULL) AND (owner_id = 'dsadsadsadsA'::bpchar))
(6 rows)

Plan after the index change:

                                                          QUERY PLAN
------------------------------------------------------------------------------------------------------------------------------
 Limit  (cost=8.32..8.32 rows=1 width=196)
   ->  Sort  (cost=8.32..8.32 rows=1 width=196)
         Sort Key: at DESC, updated_at DESC
         ->  Index Scan Backward using turip_test on balance_snapshots  (cost=0.28..8.31 rows=1 width=196)
               Index Cond: (((namespace)::text = 'org_test'::text) AND (owner_id = 'dsadsadsadsA'::bpchar) AND (at <= now()))

Summary by CodeRabbit

  • Refactor
    • Updated the internal indexing for balance tracking records with refined filtering conditions to improve query performance and data consistency.
  • Chores
    • Adjusted database migration procedures to align with the new indexing strategy, ensuring a seamless schema update.

This should help with the usage snapshot queries.
Copy link
Contributor

coderabbitai bot commented Mar 11, 2025

📝 Walkthrough

Walkthrough

The changes update the database schema and related code for managing indexes on the balance_snapshots table. In the Go code, an existing index is renamed and its column composition is modified to include the owner_id field, with an added condition ensuring records with deleted_at set are excluded. Corresponding SQL migration scripts are updated: the “up” script creates the new index while dropping outdated ones, and the “down” script reverses these modifications by reintroducing the old indexes.

Changes

Files Change Summary
openmeter/.../schema.go Renamed index balancesnapshot_namespace_at to balancesnapshot_namespace_owner_id_at, updated index columns from [1],[9] to [1],[10],[9], and added an annotation to include only rows where deleted_at IS NULL.
openmeter/.../balance_snapshot.go Modified the Indexes method: removed old indexes and added a new index combining namespace, owner_id, and at with a condition (deleted_at IS NULL); added the entsql import to support the new index annotation.
tools/migrate/migrations/20250311193204_balance-snapshot-indexes.{down,up}.sql In the up migration, dropped indexes balancesnapshot_namespace_at, balancesnapshot_namespace_balance, and balancesnapshot_namespace_balance_at and created the new index balancesnapshot_namespace_owner_id_at on (namespace, owner_id, at) with condition deleted_at IS NULL. In the down migration, reversed these changes.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 55556d1 and 5814ba1.

⛔ Files ignored due to path filters (1)
  • tools/migrate/migrations/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (4)
  • openmeter/ent/db/migrate/schema.go (1 hunks)
  • openmeter/ent/schema/balance_snapshot.go (2 hunks)
  • tools/migrate/migrations/20250311193204_balance-snapshot-indexes.down.sql (1 hunks)
  • tools/migrate/migrations/20250311193204_balance-snapshot-indexes.up.sql (1 hunks)
🔇 Additional comments (5)
openmeter/ent/schema/balance_snapshot.go (2)

6-6: Added import for new index annotation feature.

The import for "entgo.io/ent/dialect/entsql" has been added to support the index annotation feature that will be used to specify the condition on the index.


47-53: Improved index strategy for better query performance.

The changes optimize the balance snapshots query performance by:

  1. Replacing multiple specialized indexes with a single consolidated index
  2. Including owner_id in the index which aligns with the filtering pattern in queries
  3. Adding a filter condition deleted_at IS NULL to the index which reduces index size and improves lookup times for active records

This change directly addresses the PR objective of enhancing the performance of usage snapshot queries.

tools/migrate/migrations/20250311193204_balance-snapshot-indexes.up.sql (1)

1-8: SQL migration correctly implements the index changes.

The migration properly:

  1. Drops the three old indexes that are being replaced
  2. Creates the new improved index with the deleted_at IS NULL condition

This aligns correctly with the schema definition changes and follows good database migration practices.

tools/migrate/migrations/20250311193204_balance-snapshot-indexes.down.sql (1)

1-8: Down migration properly restores the original index structure.

The rollback migration correctly:

  1. Drops the new index
  2. Recreates the three original indexes

This ensures the database can be properly reverted to its previous state if needed.

openmeter/ent/db/migrate/schema.go (1)

234-240: Generated schema code reflects the index optimization.

The changes in this generated file correctly mirror the schema modifications:

  1. Renamed index to include owner_id in the name
  2. Added BalanceSnapshotsColumns[10] (owner_id) to the indexed columns
  3. Added the deleted_at IS NULL condition annotation

This confirms that the code generation pipeline is working as expected and that the schema changes are properly reflected in the database definition.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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

@turip turip requested a review from GAlexIHU March 11, 2025 19:37
@turip turip marked this pull request as ready for review March 11, 2025 19:37
@turip turip requested a review from a team as a code owner March 11, 2025 19:37
@turip turip merged commit 1bf7d32 into main Mar 12, 2025
26 of 27 checks passed
@turip turip deleted the chore/fix-entitlements-indexes branch March 12, 2025 10:05
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants