Skip to content
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

refactor: update OTLP Histogram Records #1754

Merged
merged 3 commits into from
Nov 4, 2024
Merged

Conversation

ucatbas
Copy link
Contributor

@ucatbas ucatbas commented Nov 4, 2024

Description:

This PR refactors the OTLP histogram recording logic.

Changes:

  • Removed duration histograms and added amount histograms
  • Removed a span from an if logic

Summary by CodeRabbit

Release Notes

  • New Features

    • Updated API version to v1.2.0 across all relevant documentation and specifications.
  • Bug Fixes

    • Streamlined metrics collection in various services, focusing on operation counts instead of durations.
  • Documentation

    • Enhanced clarity in API documentation by updating version numbers and descriptions related to metrics.

Copy link

coderabbitai bot commented Nov 4, 2024

Walkthrough

This pull request primarily updates the version number of the Permify API from "v1.1.9" to "v1.2.0" across multiple files, including Swagger and OpenAPI documentation, as well as internal structures. Additionally, it simplifies the metrics handling in various components by removing duration-based measurements and focusing on counting operations instead. This change affects the CheckEngineWithCache, DirectInvoker, DataServer, and SchemaServer, streamlining how cache hits and other operations are recorded.

Changes

File Path Change Summary
docs/api-reference/apidocs.swagger.json Version updated from "v1.1.9" to "v1.2.0".
docs/api-reference/openapiv2/apidocs.swagger.json Version updated from "v1.1.9" to "v1.2.0".
internal/engines/cache/check.go Removed cacheCounter and cacheHitDurationHistogram; added cacheHitHistogram.
internal/engines/cache/check_test.go Updated initialization of CheckEngineWithCache struct by removing a nil field.
internal/info.go Version constant updated from "v1.1.9" to "v1.2.0".
internal/invoke/invoke.go Removed multiple counters and duration histograms; added new histogram metrics for operations.
internal/servers/dataServer.go Changed histogram metrics to count operations instead of measuring duration; removed timing logic.
internal/servers/schemaServer.go Removed time package; changed histogram metrics to count operations instead of measuring duration.
proto/base/v1/openapi.proto Version updated from "v1.1.9" to "v1.2.0".

Possibly related PRs

🐰 In the fields of code, we hop and play,
A version change, hip-hip-hooray!
From "v1.1.9" to "v1.2.0" we leap,
Metrics refined, our data we keep.
With each little change, we grow and improve,
In the world of APIs, we find our groove! 🌟


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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 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.

@ucatbas ucatbas requested a review from tolgaOzen November 4, 2024 10:43
@tolgaOzen tolgaOzen changed the title Refactor: Update OTLP Histogram Records refactor: update OTLP Histogram Records Nov 4, 2024
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: 0

🧹 Outside diff range and nitpick comments (9)
internal/engines/cache/check.go (2)

28-28: LGTM! Good simplification of metrics.

The consolidation to a single cacheHitHistogram is a good architectural choice. Cache hit rate is typically the most important metric for cache performance analysis, making this a more focused approach.

Consider adding cache miss tracking in the future if you need to calculate hit ratios or analyze cache effectiveness more deeply.


67-68: Enhance the comment clarity.

The current comment could be more specific about what's being measured.

-		// Increase the hit count in the metrics.
+		// Record a cache hit in the OTLP histogram metrics.
internal/servers/schemaServer.go (2)

39-41: Fix incomplete metric description.

The description for write_schema histogram ends with "in", which appears to be incomplete.

-		writeSchemaHistogram: telemetry.NewHistogram(internal.Meter, "write_schema", "amount", "Number of writing schema in"),
+		writeSchemaHistogram: telemetry.NewHistogram(internal.Meter, "write_schema", "amount", "Number of schema writes"),

39-41: Consider complementing operation counts with duration metrics.

While the shift to operation counting provides valuable throughput metrics, consider maintaining both count and duration metrics for comprehensive observability. This would help in:

  • Identifying performance bottlenecks
  • Setting appropriate SLOs
  • Monitoring system health

You could implement this using OpenTelemetry's NewHistogram with different units for each metric type.

Also applies to: 84-84, 224-224, 249-249

internal/servers/dataServer.go (1)

Line range hint 50-413: Consider documenting the monitoring strategy

The shift from duration-based to count-based metrics represents a significant change in monitoring strategy. Consider:

  1. Documenting this change in monitoring documentation
  2. Updating dashboards and alerts that might depend on the removed duration metrics
  3. Ensuring observability requirements are still met with the new metrics

This will help maintain system observability and ensure smooth operations transition.

internal/invoke/invoke.go (1)

263-263: Consider adding metric attributes for consistency.

While the Check method includes detailed attributes with its histogram recording, other methods (LookupEntity, LookupEntityStream, LookupSubject, SubjectPermission) record metrics without any context. Consider adding relevant attributes for better observability.

Example implementation for LookupEntity:

-invoker.lookupEntityHistogram.Record(ctx, 1)
+invoker.lookupEntityHistogram.Record(ctx, 1,
+    metric.WithAttributeSet(
+        attribute.NewSet(
+            attribute.KeyValue{Key: "entity_type", Value: attribute.StringValue(request.GetEntityType())},
+            attribute.KeyValue{Key: "subject_type", Value: attribute.StringValue(request.GetSubject().GetType())},
+        )),
+)

Similar attribute sets should be added to other methods based on their context.

Also applies to: 304-304, 350-350, 396-396

internal/engines/cache/check_test.go (3)

44-44: Add parameter documentation for CheckEngineWithCache initialization.

The struct initialization CheckEngineWithCache{nil, nil, cache, nil} appears multiple times but lacks clear documentation about what each parameter represents. Consider adding comments to explain the purpose of each parameter for better maintainability.

Also applies to: 94-94, 144-144, 288-288, 323-323


Line range hint 1-1200: Consider refactoring test setup for better maintainability.

The test file has several areas that could be improved:

  1. Test data setup is duplicated across test cases. Consider extracting common setup code into helper functions.
  2. Cache configuration (ristretto.New()) is repeated in each test. Consider creating a helper function or using BeforeEach hooks.
  3. Some test cases have duplicate assertions that could be consolidated.

These changes would improve maintainability and reduce the likelihood of inconsistencies.


Line range hint 1-1200: Consider adding tests for additional scenarios.

While the test coverage is comprehensive for permission checks, consider adding tests for:

  1. Cache eviction and invalidation scenarios
  2. Error cases for cache operations
  3. Concurrent access to the cache

These additional tests would help ensure the cache behaves correctly under all conditions.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 7679460 and eba5a1f.

⛔ Files ignored due to path filters (1)
  • pkg/pb/base/v1/openapi.pb.go is excluded by !**/*.pb.go
📒 Files selected for processing (9)
  • docs/api-reference/apidocs.swagger.json (1 hunks)
  • docs/api-reference/openapiv2/apidocs.swagger.json (1 hunks)
  • internal/engines/cache/check.go (3 hunks)
  • internal/engines/cache/check_test.go (5 hunks)
  • internal/info.go (1 hunks)
  • internal/invoke/invoke.go (8 hunks)
  • internal/servers/dataServer.go (8 hunks)
  • internal/servers/schemaServer.go (4 hunks)
  • proto/base/v1/openapi.proto (1 hunks)
✅ Files skipped from review due to trivial changes (3)
  • docs/api-reference/apidocs.swagger.json
  • docs/api-reference/openapiv2/apidocs.swagger.json
  • proto/base/v1/openapi.proto
🔇 Additional comments (13)
internal/info.go (2)

26-26: LGTM: Version bump follows semantic versioning.

The minor version increment (v1.1.9 → v1.2.0) appropriately reflects the internal improvements being made to the OTLP histogram recording system, as these changes add new functionality in a backward-compatible manner.


26-26: Verify version consistency across the codebase.

Let's ensure this version update is consistently applied across all relevant files.

✅ Verification successful

Version v1.2.0 is consistently applied across the codebase

The version string "v1.2.0" is consistently used across all relevant files:

  • internal/info.go: Version constant
  • proto/base/v1/openapi.proto: API version
  • docs/api-reference/apidocs.swagger.json: API documentation
  • docs/api-reference/openapiv2/apidocs.swagger.json: OpenAPI v2 documentation

No occurrences of the old version (v1.1.9) were found.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check for any remaining occurrences of the old version
# and verify the new version is consistently applied.

echo "Checking for any remaining occurrences of v1.1.9..."
rg "v1\.1\.9"

echo -e "\nVerifying v1.2.0 is consistently applied in key files..."
# Common locations for version strings
for pattern in "version.*1\.2\.0" "v1\.2\.0"
do
  rg -g "*.{json,yaml,yml,proto,go}" "$pattern"
done

Length of output: 874

internal/engines/cache/check.go (2)

39-42: LGTM! Clear and well-structured initialization.

The metric initialization is clear with appropriate naming and units.


Line range hint 28-42: Verify telemetry consumers compatibility.

The change from duration-based to count-based metrics might affect downstream telemetry consumers (e.g., monitoring dashboards, alerts).

✅ Verification successful

Metric change is consistent with codebase patterns

The change from duration-based to count-based metrics aligns with the existing telemetry implementation:

  • All histograms in the codebase use the same count-based pattern with "amount" unit
  • The telemetry.NewHistogram helper consistently creates Int64Histogram with count-based metrics
  • No duration-based histograms were found in the codebase
  • Metric export configuration in example.config.yaml is generic and not tied to specific metric types
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for any remaining duration-based histogram references
echo "Checking for any remaining duration histogram references..."
rg -i "duration.*histogram" --type go

echo "Checking for potential metric consumers..."
rg -l "cache_hit_duration" --type yaml --type json

Length of output: 314


Script:

#!/bin/bash
# Let's try a broader search to understand the telemetry setup and consumers

# Check for metric-related configurations and consumers
echo "Checking for metric configurations..."
rg -i "metric|telemetry" --type yaml --type json -A 5

# Look for other histogram usages to understand the pattern
echo "Checking histogram usage patterns..."
rg -i "histogram" --type go -A 2

# Check for monitoring or observability related files
echo "Looking for monitoring configurations..."
fd -e yaml -e yml -e json . | grep -i "monitor\|metric\|telemetry\|observ"

# Search for the specific metric name
echo "Searching for cache_hit metric usage..."
rg "cache_hit" --type go --type yaml --type json -A 2

Length of output: 9136

internal/servers/schemaServer.go (3)

84-84: LGTM!

The histogram recording is correctly placed after error handling and records successful schema writes.


224-224: LGTM!

The histogram recording is correctly placed after error handling and records successful schema reads.


249-249: LGTM!

The histogram recording is correctly placed after both error checks and records successful schema listings.

internal/servers/dataServer.go (2)

101-101: LGTM: Consistent metric recording pattern

The histogram recording points are consistently placed:

  • After successful operation completion
  • Before returning the response
  • Using a constant value of 1 for counting

This ensures accurate tracking of successful operations.

Also applies to: 150-150, 248-248, 315-315, 345-345, 375-375, 413-413


50-56: Consider the impact of removing duration metrics

While switching from duration to count-based metrics simplifies the monitoring, it removes visibility into operation latency. This could make it harder to:

  1. Identify performance bottlenecks
  2. Set meaningful SLOs
  3. Debug timing-related issues

Consider maintaining both metrics types or ensuring alternative latency monitoring is in place.

internal/invoke/invoke.go (4)

9-9: LGTM: Import addition is appropriate.

The added metric import aligns with the refactoring to use histograms for metrics collection.


89-99: LGTM: Constructor updates maintain consistency.

The histogram initializations follow a consistent pattern with clear metric names and descriptions. The use of "amount" as the unit type is appropriate for counting operations.


114-120: LGTM: Well-structured metric recording with context.

The Check method's histogram recording includes relevant attributes that provide valuable context for metrics analysis.


71-74: LGTM: Histogram field changes align with metrics refactoring.

The new histogram fields appropriately replace the removed counters and duration histograms, maintaining a consistent naming pattern.

✅ Verification successful

The previous search might have been too specific. Let's broaden it to catch any remaining references to the old metric types and verify the changes are complete.


The previous results showed mostly unrelated matches. Let's focus specifically on the metrics implementation in the file under review.


The duration histograms have been successfully replaced with amount histograms

The verification confirms that:

  • All old duration histograms have been removed from the file
  • New Int64Histogram fields are properly implemented
  • No remaining references to the old metric types exist in the file
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Verify that all duration histograms have been removed and replaced with amount histograms
rg -l "DurationHistogram|Counter.*api\.Int64Counter" .

Length of output: 56


Script:

#!/bin/bash
# Search for any remaining duration or counter metrics in the codebase
rg -i "duration.*histogram|counter" .

# Also check for any metric registrations or initializations
ast-grep --pattern 'NewInt64(Counter|DurationHistogram)'

Length of output: 24817


Script:

#!/bin/bash
# Let's check the specific file for any old metric-related code and the new histogram implementations
rg -A 2 "Int64(Counter|DurationHistogram|Histogram)" internal/invoke/invoke.go

# Also check for metric initialization in this file
ast-grep --pattern 'NewInt64$_($_, $_)'

Length of output: 530

@tolgaOzen tolgaOzen merged commit e1f6fc4 into master Nov 4, 2024
12 of 13 checks passed
@tolgaOzen tolgaOzen deleted the ufuk/monitoring-histograms branch November 4, 2024 12:17
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