Skip to content

refactor: high watermark cache to filter framework - #3036

Merged
turip merged 2 commits into
mainfrom
refactor/high-watermark-cache-to-filter-framework
Jun 26, 2025
Merged

turip merged 2 commits into
mainfrom
refactor/high-watermark-cache-to-filter-framework

Conversation

@turip

@turip turip commented Jun 25, 2025 •

Copy link
Copy Markdown
Member

Overview

Move the high watermark cache to filter framework. This will allows us to have a new redis based backend for the high watermark cache, which in turn would make sure that the recalculator job and the consumer shares high watermark cache state.

Summary by CodeRabbit

  • New Features

    • Introduced a high watermark cache filter to improve entitlement event processing efficiency and prevent reprocessing of older events.
    • Centralized event timestamp validation and enhanced filtering with richer context for entitlement events.
  • Improvements

    • Updated entitlement filtering and event handling to use structured requests that include event time and operation type, enabling more precise processing.
    • Consistent timestamping and recording of entitlement recalculation events for improved traceability.
    • Enhanced error handling and validation for entitlement event processing.
  • Refactor

    • Removed legacy high watermark cache logic and replaced it with a more robust filtering-based approach.
    • Standardized type usage and updated function signatures for improved maintainability.

@coderabbitai

coderabbitai Bot commented Jun 25, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This change refactors entitlement event filtering and recalculation logic. It introduces a structured filter request for entitlement scope checks, adds a high watermark cache filter, centralizes event time validation, and updates event processing to consistently handle calculation timestamps. High watermark cache logic is removed from the worker and replaced with the new filter-based approach.

Changes

Files/Paths Change Summary
cmd/jobs/entitlement/recalculatesnapshots.go Passes current time to the Recalculate method, updating the function call to include a timestamp argument.
openmeter/entitlement/balanceworker/worker.go
.../ingesthandler.go
.../entitlementhandler.go
Removes high watermark cache logic and related metrics from the worker; replaces local NamespacedID alias with pkgmodels.NamespacedID throughout event handler and ingest handler functions. Centralizes event timestamp validation.
openmeter/entitlement/balanceworker/filters.go
.../filters/filter.go
.../filters/notifications.go
Refactors filter interfaces to accept a structured EntitlementFilterRequest (with entitlement, event time, and operation). Adds a method for recording last calculation time. Updates notification filter logic to use the new request struct. Inverts filter execution logic for scope checks.
openmeter/entitlement/balanceworker/filters/highwatermark.go Adds a new in-memory high watermark cache filter as a filter implementation, managing event deduplication and deletion state per entitlement. Implements filter and calculation time recorder interfaces.
openmeter/entitlement/balanceworker/recalculate.go Updates the recalculation process to accept a start timestamp, passes this through entitlement filtering and event sending, and records calculation times using the new filter interface. Modifies event sending methods to return calculation timestamps.

Possibly related PRs

  • openmeterio/openmeter#2928: Adds notification service integration and notification-based filtering to the balance worker, introducing TTL cache for notifications and modifying entitlement recalculation/filtering logic, which overlaps with the filter and recalculation changes in this PR.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2


📜 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 49cd5f4 and d6b5b8c.

📒 Files selected for processing (1)
  • openmeter/entitlement/balanceworker/entitlementhandler.go (6 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • openmeter/entitlement/balanceworker/entitlementhandler.go
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: E2E
  • GitHub Check: Quickstart
  • GitHub Check: CI
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Test
  • GitHub Check: Lint
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
✨ 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.

@turip
turip force-pushed the refactor/high-watermark-cache-to-filter-framework branch 2 times, most recently from 543773e to 1d766d6 Compare June 25, 2025 09:08
@turip turip added release-note/ignore Ignore this change when generating release notes area/entitlements area/notification labels Jun 25, 2025
@turip
turip marked this pull request as ready for review June 25, 2025 09:09
@turip
turip requested a review from a team as a code owner June 25, 2025 09:09

@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 (2)
openmeter/entitlement/balanceworker/filters.go (1)

80-82: Minor: Consider consistent struct initialization

For better readability, consider using a pointer directly:

-return EntitlementFilters{
-	filters: []filters.NamedFilter{notificationFilter, highWatermarkCache},
-}.WithMetrics(cfg.MetricMeter)
+filters := &EntitlementFilters{
+	filters: []filters.NamedFilter{notificationFilter, highWatermarkCache},
+}
+return filters.WithMetrics(cfg.MetricMeter)
openmeter/entitlement/balanceworker/filters/filter.go (1)

52-56: Consider adding validation to RecordLastCalculationRequest.

For consistency with EntitlementFilterRequest, consider adding a Validate() method to ensure required fields are present.

type RecordLastCalculationRequest struct {
	Entitlement  entitlement.Entitlement
	CalculatedAt time.Time
	IsDeleted    bool
}
+
+func (r RecordLastCalculationRequest) Validate() error {
+	errs := []error{}
+
+	if r.Entitlement.ID == "" {
+		errs = append(errs, fmt.Errorf("entitlement.id is required"))
+	}
+
+	if r.Entitlement.Namespace == "" {
+		errs = append(errs, fmt.Errorf("entitlement.namespace is required"))
+	}
+
+	if r.CalculatedAt.IsZero() {
+		errs = append(errs, fmt.Errorf("calculatedAt is required"))
+	}
+
+	return errors.Join(errs...)
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1c62942 and 1d766d6.

📒 Files selected for processing (9)
  • cmd/jobs/entitlement/recalculatesnapshots.go (2 hunks)
  • openmeter/entitlement/balanceworker/entitlementhandler.go (6 hunks)
  • openmeter/entitlement/balanceworker/filters.go (5 hunks)
  • openmeter/entitlement/balanceworker/filters/filter.go (1 hunks)
  • openmeter/entitlement/balanceworker/filters/highwatermarkinmem.go (1 hunks)
  • openmeter/entitlement/balanceworker/filters/notifications.go (2 hunks)
  • openmeter/entitlement/balanceworker/ingesthandler.go (4 hunks)
  • openmeter/entitlement/balanceworker/recalculate.go (6 hunks)
  • openmeter/entitlement/balanceworker/worker.go (7 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: Quickstart
  • GitHub Check: CI
  • GitHub Check: Commit hooks
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: Build
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: Test
  • GitHub Check: Analyze (go)
🔇 Additional comments (10)
cmd/jobs/entitlement/recalculatesnapshots.go (1)

4-5: LGTM!

The addition of the timestamp parameter to track recalculation start time is appropriate and correctly implemented.

Also applies to: 27-27

openmeter/entitlement/balanceworker/ingesthandler.go (1)

12-12: LGTM!

Consistent replacement of local NamespacedID type with the shared pkgmodels.NamespacedID improves code consistency across the codebase.

Also applies to: 33-33, 56-56, 79-84

openmeter/entitlement/balanceworker/filters/notifications.go (1)

79-106: LGTM!

The method signature update to accept EntitlementFilterRequest aligns well with the new filter framework design, and the validation check ensures request integrity.

openmeter/entitlement/balanceworker/worker.go (1)

98-98: LGTM!

The removal of the high watermark cache components and consistent replacement of the local NamespacedID type with pkgmodels.NamespacedID successfully decouples the cache logic from the worker implementation.

Also applies to: 132-136, 191-191, 202-202, 214-214, 226-226, 238-238

openmeter/entitlement/balanceworker/filters.go (1)

75-82: Well-structured filter chain implementation!

The addition of the high watermark cache filter and the new RecordLastCalculation method successfully centralizes the calculation time tracking within the filter framework. The inverted filter logic that returns false immediately is more efficient.

Also applies to: 123-137, 155-169, 171-183

openmeter/entitlement/balanceworker/filters/filter.go (1)

13-39: Well-structured request object with comprehensive validation.

The EntitlementFilterRequest struct and its validation method are well-implemented. Good use of errors.Join for combining multiple validation errors.

openmeter/entitlement/balanceworker/filters/highwatermarkinmem.go (1)

1-88: Well-implemented in-memory high watermark cache filter.

The implementation is clean and follows good practices:

  • Proper use of LRU cache for memory management
  • Correct clock drift handling for distributed systems
  • Safe defaults (returning true for cache misses)
  • Clear separation of concerns with the filter interfaces
openmeter/entitlement/balanceworker/entitlementhandler.go (1)

39-45: Good addition of validation method.

The validation ensures eventAt is required, preventing potential issues downstream.

openmeter/entitlement/balanceworker/recalculate.go (2)

148-198: Well-structured timestamp propagation and error handling.

The changes properly propagate the recalculation timestamp through the processing pipeline and handle errors appropriately using errors.Join for aggregating multiple errors.

Also applies to: 200-240


242-244: Clean refactoring to return calculation timestamps.

The introduction of sendEntitlementEventResult and the consistent updates to all send methods provide a clean way to track and propagate calculation timestamps back to the caller.

Also applies to: 246-355

Move the high watermark cache to filter framework. This allows us to
have a new redis based backend for the high watermark cache, which
in turn would make sure that the recalculator job and the consumer
shares high watermark cache state.
@turip
turip force-pushed the refactor/high-watermark-cache-to-filter-framework branch from 1d766d6 to 49cd5f4 Compare June 25, 2025 09:25
@turip
turip enabled auto-merge (squash) June 26, 2025 08:07
@turip
turip merged commit ab2020c into main Jun 26, 2025
@turip
turip deleted the refactor/high-watermark-cache-to-filter-framework branch June 26, 2025 13:59
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/entitlements area/notification 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