Skip to content

refactor(streaming): resolve customer_id with map - #3259

Merged
hekike merged 2 commits into
mainfrom
feat/event-list-customer-id-with-map
Aug 24, 2025
Merged

hekike merged 2 commits into
mainfrom
feat/event-list-customer-id-with-map

Conversation

@hekike

@hekike hekike commented Aug 23, 2025 •

Copy link
Copy Markdown
Contributor

Refactor customer_id select.

Summary by CodeRabbit

  • Refactor
    • Simplified how event and meter queries build filters and include customer IDs, improving consistency and maintainability.
  • Bug Fixes
    • Resolved inconsistencies when combining customer and subject filters, producing more reliable query results.
  • Tests
    • Updated tests to cover new customer-to-subject mapping and combined filter scenarios to ensure query behavior remains correct.

@coderabbitai

coderabbitai Bot commented Aug 23, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Decouples subject and customer filters, replaces CASE-based subject→customer_id with a WITH map, and shifts helper functions to mutate the sqlbuilder.SelectBuilder directly; applies these changes across event and meter ClickHouse query builders and their tests.

Changes

Cohort / File(s) Summary
Event query refactor
openmeter/streaming/clickhouse/event_query.go, openmeter/streaming/clickhouse/event_query_v2.go
Split subject and customer filtering flows (subjectWhere no longer accepts customers); replace selectColumns accumulation with direct query mutations; use selectCustomerIdColumn and customersWhere to mutate the query builder.
Query helper changes
openmeter/streaming/clickhouse/queryhelper.go
Replace CASE-based subject→customer_id with a WITH map CTE; rename/reshape helpers: selectCustomerIdColumns → selectCustomerIdColumn (now mutates/returns the builder), customersWhereExpr → customersWhere (applies Where on builder), subjectWhere signature updated to drop customers.
Meter query updates
openmeter/streaming/clickhouse/meter_query.go
Move customer_id selection to selectCustomerIdColumn mutation; replace method-based subject filter with top-level customersWhere and subjectWhere calls and reorder filter application.
Tests updated for new SQL
openmeter/streaming/clickhouse/event_query_v2_test.go, openmeter/streaming/clickhouse/meter_query_test.go
Update expectations from CASE-based to WITH map-based customer_id derivation; adjust expected SQL to use the map and access customer_id via map indexing; argument lists largely unchanged except additional subject filter args where applicable.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.


📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 3add88c and 31c2751.

📒 Files selected for processing (1)
  • openmeter/streaming/clickhouse/queryhelper.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • openmeter/streaming/clickhouse/queryhelper.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Analyze (go)
  • GitHub Check: Code Generators
  • GitHub Check: Lint
  • GitHub Check: Migration Checks
  • GitHub Check: Test
  • GitHub Check: Build
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/event-list-customer-id-with-map

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

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

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@hekike
hekike requested a review from tothandras August 23, 2025 21:25
@hekike
hekike marked this pull request as ready for review August 23, 2025 21:25
@hekike
hekike requested a review from a team as a code owner August 23, 2025 21:25
@hekike hekike added release-note/ignore Ignore this change when generating release notes area/processor labels Aug 23, 2025
Base automatically changed from feat/event-list-customer-id to main August 23, 2025 21:37
@hekike
hekike force-pushed the feat/event-list-customer-id-with-map branch from 1995d33 to 3add88c Compare August 23, 2025 23:24
@hekike
hekike enabled auto-merge (squash) August 23, 2025 23:24

@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

🧹 Nitpick comments (4)
openmeter/streaming/clickhouse/queryhelper.go (2)

19-30: Consider validating empty subject keys.

While the code handles customers with subject keys correctly, it might be worth adding validation or filtering for customers with empty SubjectKeys arrays to avoid unnecessary map entries.

 for _, customer := range customers {
+    if len(customer.GetUsageAttribution().SubjectKeys) == 0 {
+        continue
+    }
     // Add each subject key to the map and map it to the customer id
     for _, subjectKey := range customer.GetUsageAttribution().SubjectKeys {
         subjectSQL := fmt.Sprintf("'%s'", sqlbuilder.Escape(subjectKey))
         customerIDSQL := fmt.Sprintf("'%s'", sqlbuilder.Escape(customer.GetUsageAttribution().ID))
 
         values = append(values, subjectSQL, customerIDSQL)
     }
 }

32-37: Consider handling edge case of empty customer list.

When customers is empty, the map will be created with no entries. While this should work, it might be cleaner to skip the WITH clause entirely in such cases.

+// Return early if no customers provided
+if len(customers) == 0 {
+    return query
+}
+
 mapAs := "subject_to_customer_id"
 mapSQL := fmt.Sprintf("WITH map(%s) as %s", strings.Join(values, ", "), mapAs)
openmeter/streaming/clickhouse/event_query.go (2)

161-163: Use the same qualified tableName here as well; also confirm count-estimate intent with customersWhere.

For consistency with FROM, pass tableName into both helpers. Additionally, the comment above toCountRowSQL mentions filtering only by columns in table order for estimation efficiency. Ensure customersWhere(...) constrains subject (which is in the ORDER BY tuple) rather than introducing computed predicates that could hurt the estimate performance.

Apply this diff:

-	query = subjectWhere(d.EventsTableName, subjects, query)
-	query = customersWhere(d.EventsTableName, customers, query)
+	query = subjectWhere(tableName, subjects, query)
+	query = customersWhere(tableName, customers, query)

You can quickly verify the generated WHERE parts for both functions using the existing tests or by logging the built SQL for representative inputs (subject-only, customers-only, and both).


97-99: Use the same tableName in helper filters to keep column qualifications in sync

Passing d.EventsTableName to subjectWhere/customersWhere can misqualify columns when the FROM clause uses a different identifier (e.g. fully-qualified name or alias). Since both helpers build column references via columnFactory(eventsTableName), it’s safer to pass the exact tableName used in FROM.

• File: openmeter/streaming/clickhouse/event_query.go
Location: around lines 97–99

Suggested refactor (optional):

-   query = subjectWhere(d.EventsTableName, subjects, query)
-   query = customersWhere(d.EventsTableName, customers, query)
+   query = subjectWhere(tableName, subjects, query)
+   query = customersWhere(tableName, customers, query)

This ensures that columns in filters always align with the table identifier in the FROM clause.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled
  • Linear integration is disabled

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 558f7ac and 3add88c.

📒 Files selected for processing (6)
  • openmeter/streaming/clickhouse/event_query.go (3 hunks)
  • openmeter/streaming/clickhouse/event_query_v2.go (3 hunks)
  • openmeter/streaming/clickhouse/event_query_v2_test.go (1 hunks)
  • openmeter/streaming/clickhouse/meter_query.go (2 hunks)
  • openmeter/streaming/clickhouse/meter_query_test.go (2 hunks)
  • openmeter/streaming/clickhouse/queryhelper.go (2 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
openmeter/streaming/clickhouse/queryhelper.go (3)
api/client/javascript/src/client/schemas.ts (1)
  • Customer (10856-10856)
api/api.gen.go (1)
  • Customer (2165-2215)
api/client/go/client.gen.go (1)
  • Customer (1995-2045)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (7)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: Test
  • GitHub Check: Code Generators
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
🔇 Additional comments (11)
openmeter/streaming/clickhouse/event_query_v2_test.go (1)

150-150: LGTM! Map-based customer_id derivation is more efficient.

The change from CASE-based to map-based customer_id derivation is a solid improvement. The map approach simplifies the SQL and should perform better, especially with many subject-to-customer mappings.

openmeter/streaming/clickhouse/meter_query.go (2)

200-204: Good refactoring: customer_id selection moved to query mutation phase.

Moving the customer_id column selection from the pre-built selectColumns array to a direct query mutation is cleaner and more consistent with the new helper pattern.


267-268: Consistent use of top-level filter helpers.

The migration from method-based filtering to top-level helper functions (customersWhere and subjectWhere) improves code organization and reusability across different query builders.

openmeter/streaming/clickhouse/meter_query_test.go (2)

294-294: Test correctly reflects the new map-based approach.

The test expectation properly validates the new SQL generation with the WITH map clause for customer_id derivation.


363-364: Filter combination test is properly updated.

The test correctly includes both subject filters in the WHERE clause when both FilterCustomer and FilterSubject are specified, maintaining the AND relationship between them.

openmeter/streaming/clickhouse/event_query_v2.go (3)

26-31: Clean column selection with conditional customer_id inclusion.

The explicit column selection followed by conditional customer_id inclusion via selectCustomerIdColumn is more readable than the previous dynamic array approach.


60-61: Consistent filter application pattern.

Using customersWhere to mutate the query directly aligns well with the overall refactoring pattern and eliminates the need for intermediate expression strings.


139-140: Count query correctly applies customer filter.

The count query maintains consistency with the main query by using the same customersWhere helper.

openmeter/streaming/clickhouse/queryhelper.go (3)

13-43: Efficient map-based customer_id derivation implementation.

The new implementation using ClickHouse's map function is elegant and efficient. The WITH clause approach properly isolates the mapping logic.


45-61: Clean separation of customer filtering logic.

The customersWhere function properly encapsulates the customer filtering logic and returns the mutated query builder, following the fluent interface pattern.


63-81: Subject filtering correctly decoupled from customer filtering.

The removal of the customers parameter from subjectWhere properly separates concerns, making the function's purpose clearer.

@hekike
hekike merged commit d672afd into main Aug 24, 2025
@hekike
hekike deleted the feat/event-list-customer-id-with-map branch August 24, 2025 12:28
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/processor release-note/ignore Ignore this change when generating release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants