Skip to content

feat: add minute granularity - This should be merged before key details#3240

Merged
ogzhanolguncu merged 4 commits intomainfrom
add-minute-granularity-for-verifications
May 14, 2025
Merged

feat: add minute granularity - This should be merged before key details#3240
ogzhanolguncu merged 4 commits intomainfrom
add-minute-granularity-for-verifications

Conversation

@ogzhanolguncu
Copy link
Contributor

@ogzhanolguncu ogzhanolguncu commented May 12, 2025

What does this PR do?

This PR adds minute granularity for the upcoming Keys Details page and better chart results. We have to merge this first so we can have some data before we actually enable the minute granularity for charts.

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • Chore (refactoring code, technical debt, workflow improvements)
  • Enhancement (small improvements)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How should this be tested?

  • Check /apis page charts
  • Check /keys outcome chart and active keys chart

Checklist

Required

  • Filled out the "How to test" section in this PR
  • Read Contributing Guide
  • Self-reviewed my own code
  • Commented on my code in hard-to-understand areas
  • Ran pnpm build
  • Ran pnpm fmt
  • Checked for warnings, there are none
  • Removed all console.logs
  • Merged the latest changes from main onto my branch with git pull origin main
  • My changes don't cause any responsiveness issues

Appreciated

  • If a UI change was made: Added a screen recording or screenshots to this PR
  • Updated the Unkey Docs if changes were necessary

Summary by CodeRabbit

  • New Features

    • Added support for minute-level, 5-minute, and 30-minute timeseries granularity for verification and active key data, enabling finer detail in analytics and dashboards.
    • Introduced new database tables and materialized views to efficiently store and aggregate verification events at minute-level resolution.
  • Improvements

    • Enhanced flexibility in timeseries granularity selection for verification data, allowing more detailed analysis for short time ranges.

@changeset-bot
Copy link

changeset-bot bot commented May 12, 2025

⚠️ No Changeset found

Latest commit: 09b3786

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@vercel
Copy link

vercel bot commented May 12, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
dashboard ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 13, 2025 10:23am
1 Skipped Deployment
Name Status Preview Comments Updated (UTC)
engineering ⬜️ Ignored (Inspect) Visit Preview May 13, 2025 10:23am

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 12, 2025

📝 Walkthrough

Walkthrough

The changes introduce minute-level granularity support for verification and active key timeseries queries, including new ClickHouse tables and materialized views for per-minute aggregation. The backend utilities and query functions are extended to allow selection of minute, five-minute, and thirty-minute intervals, with optional control over their usage in the granularity utility.

Changes

File(s) Change Summary
apps/dashboard/lib/trpc/routers/utils/granularity.ts Added an optional boolean parameter allowMinutelyForVerifications to getTimeseriesGranularity, enabling minutely-level granularities for "forVerifications" context when set.
internal/clickhouse/schema/050_create_verifications.key_verifications_per_minute_v1.sql
go/pkg/clickhouse/schema/databases/001_verifications/021_key_verifications_per_minute_v1.sql
Created a new ClickHouse table verifications.key_verifications_per_minute_v1 to store per-minute aggregated verification event data using the SummingMergeTree engine.
internal/clickhouse/schema/051_create_verifications.key_verifications_per_minute_mv_v1.sql
go/pkg/clickhouse/schema/databases/001_verifications/022_key_verifications_per_minute_mv_v1.sql
Added a materialized view verifications.key_verifications_per_minute_mv_v1 to aggregate raw verification events into per-minute summaries, grouping and counting by relevant columns.
internal/clickhouse/src/index.ts Added minute-based timeseries data retrieval functions (perMinute, per5Minutes, per30Minutes) for both verifications and active keys to the ClickHouse class, organizing them by granularity.
internal/clickhouse/src/keys/active_keys.ts Introduced new minute-based intervals and corresponding exported querier functions for active keys: getMinutelyActiveKeysTimeseries, getFiveMinutelyActiveKeysTimeseries, and getThirtyMinutelyActiveKeysTimeseries. Updated interval mappings and grouped code by granularity.
internal/clickhouse/src/verifications.ts Added minute-based intervals and exported functions for verification timeseries: getMinutelyVerificationTimeseries, getFiveMinutelyVerificationTimeseries, and getThirtyMinutelyVerificationTimeseries. Updated mappings and grouped code by granularity.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant DashboardAPI
    participant GranularityUtil
    participant ClickHouse
    participant ClickHouseDB

    Client->>DashboardAPI: Request verification timeseries (with allowMinutelyForVerifications)
    DashboardAPI->>GranularityUtil: getTimeseriesGranularity(params, allowMinutelyForVerifications)
    GranularityUtil-->>DashboardAPI: Return selected granularity (minute, 5min, 30min, hour, etc.)
    DashboardAPI->>ClickHouse: Query timeseries via appropriate function (e.g., perMinute)
    ClickHouse->>ClickHouseDB: Query per-minute (or selected) table/materialized view
    ClickHouseDB-->>ClickHouse: Return aggregated timeseries data
    ClickHouse-->>DashboardAPI: Return timeseries data
    DashboardAPI-->>Client: Respond with timeseries data
Loading

Suggested reviewers

  • perkinsjr
  • mcstepp
  • chronark

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.


📜 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 d8f7838 and 09b3786.

📒 Files selected for processing (2)
  • internal/clickhouse/src/keys/active_keys.ts (4 hunks)
  • internal/clickhouse/src/verifications.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/clickhouse/src/keys/active_keys.ts
  • internal/clickhouse/src/verifications.ts
⏰ Context from checks skipped due to timeout of 90000ms (19)
  • GitHub Check: Test Go API Local / Test (Shard 3/8)
  • GitHub Check: Test Go API Local / Test (Shard 8/8)
  • GitHub Check: Test Go API Local / Test (Shard 1/8)
  • GitHub Check: Test Go API Local / Test (Shard 7/8)
  • GitHub Check: Test Go API Local / Test (Shard 4/8)
  • GitHub Check: Test Go API Local / Test (Shard 5/8)
  • GitHub Check: Test Go API Local / Test (Shard 6/8)
  • GitHub Check: Test Go API Local / Test (Shard 2/8)
  • GitHub Check: Test Agent Local / test_agent_local
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Build / Build
  • GitHub Check: Test Packages / Test ./apps/dashboard
  • GitHub Check: Test Packages / Test ./packages/hono
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test Packages / Test ./internal/billing
  • GitHub Check: Test Packages / Test ./packages/api
  • GitHub Check: autofix
  • GitHub Check: Analyze (javascript-typescript)
✨ 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.

@github-actions
Copy link
Contributor

github-actions bot commented May 12, 2025

Thank you for following the naming conventions for pull request titles! 🙏

Copy link
Contributor

@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 (2)
apps/dashboard/lib/trpc/routers/utils/granularity.ts (2)

55-56: Document parameter usage and future plans.

The comment indicates this parameter is temporary and will be removed after the key details feature is merged. Consider adding more context about why this approach was chosen and what will replace it in the future.


97-103: Simplify redundant conditions in the time range logic.

There are redundant conditions that always result in the same "perHour" granularity:

  • Lines 97-100 all set granularity to "perHour" for time ranges between 1-3 days
  • Lines 101-102 set granularity to "perHour" for time ranges between 8-16 hours

These could be simplified to reduce code complexity.

-        if (timeRange >= DAY_IN_MS * 3) {
-          granularity = "perHour";
-        } else if (timeRange >= DAY_IN_MS) {
-          granularity = "perHour";
-        } else if (timeRange >= HOUR_IN_MS * 16) {
-          granularity = "perHour";
+        if (timeRange >= HOUR_IN_MS * 16) {
+          granularity = "perHour";
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c824e5f and 21b320e.

📒 Files selected for processing (6)
  • apps/dashboard/lib/trpc/routers/utils/granularity.ts (2 hunks)
  • internal/clickhouse/schema/050_create_verifications.key_verifications_per_minute_v1.sql (1 hunks)
  • internal/clickhouse/schema/051_create_verifications.key_verifications_per_minute_mv_v1.sql (1 hunks)
  • internal/clickhouse/src/index.ts (3 hunks)
  • internal/clickhouse/src/keys/active_keys.ts (8 hunks)
  • internal/clickhouse/src/verifications.ts (5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
apps/dashboard/lib/trpc/routers/utils/granularity.ts (1)
apps/dashboard/lib/trpc/routers/utils/constants.ts (2)
  • DAY_IN_MS (2-2)
  • HOUR_IN_MS (1-1)
internal/clickhouse/src/index.ts (2)
internal/clickhouse/src/verifications.ts (12)
  • getMinutelyVerificationTimeseries (510-512)
  • getFiveMinutelyVerificationTimeseries (513-515)
  • getThirtyMinutelyVerificationTimeseries (516-518)
  • getHourlyVerificationTimeseries (521-523)
  • getTwoHourlyVerificationTimeseries (524-526)
  • getFourHourlyVerificationTimeseries (527-529)
  • getSixHourlyVerificationTimeseries (530-532)
  • getTwelveHourlyVerificationTimeseries (533-535)
  • getDailyVerificationTimeseries (538-540)
  • getThreeDayVerificationTimeseries (541-543)
  • getWeeklyVerificationTimeseries (544-546)
  • getMonthlyVerificationTimeseries (549-551)
internal/clickhouse/src/keys/active_keys.ts (11)
  • getMinutelyActiveKeysTimeseries (291-293)
  • getFiveMinutelyActiveKeysTimeseries (294-296)
  • getThirtyMinutelyActiveKeysTimeseries (297-299)
  • getHourlyActiveKeysTimeseries (302-304)
  • getTwoHourlyActiveKeysTimeseries (305-307)
  • getFourHourlyActiveKeysTimeseries (308-310)
  • getSixHourlyActiveKeysTimeseries (311-313)
  • getTwelveHourlyActiveKeysTimeseries (314-316)
  • getDailyActiveKeysTimeseries (319-321)
  • getThreeDayActiveKeysTimeseries (322-324)
  • getWeeklyActiveKeysTimeseries (325-327)
⏰ Context from checks skipped due to timeout of 90000ms (19)
  • GitHub Check: Test Go API Local / Test (Shard 4/8)
  • GitHub Check: Test Go API Local / Test (Shard 8/8)
  • GitHub Check: Test Go API Local / Test (Shard 7/8)
  • GitHub Check: Test Go API Local / Test (Shard 5/8)
  • GitHub Check: Test Go API Local / Test (Shard 3/8)
  • GitHub Check: Test Go API Local / Test (Shard 6/8)
  • GitHub Check: Test Go API Local / Test (Shard 2/8)
  • GitHub Check: Test Go API Local / Test (Shard 1/8)
  • GitHub Check: Build / Build
  • GitHub Check: Test API / API Test Local
  • GitHub Check: Test Packages / Test ./packages/api
  • GitHub Check: Test Packages / Test ./packages/rbac
  • GitHub Check: Test Packages / Test ./packages/cache
  • GitHub Check: Test Packages / Test ./packages/hono
  • GitHub Check: Test Packages / Test ./packages/nextjs
  • GitHub Check: Test Packages / Test ./apps/dashboard
  • GitHub Check: Test Packages / Test ./internal/clickhouse
  • GitHub Check: autofix
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (18)
internal/clickhouse/schema/051_create_verifications.key_verifications_per_minute_mv_v1.sql (1)

1-23: LGTM! Well-structured materialized view for minute-level aggregation.

The materialized view correctly:

  • Aggregates raw verification data at minute-level granularity
  • Groups by all relevant dimensions
  • Uses toStartOfMinute for proper timestamp bucketing
  • Targets the appropriate table
internal/clickhouse/schema/050_create_verifications.key_verifications_per_minute_v1.sql (1)

1-15: LGTM! Schema is well-designed for minute-level aggregation.

The table structure is appropriately designed with:

  • SummingMergeTree engine for efficient aggregation workloads
  • Proper columns for all required dimensions
  • Effective ordering for query performance
internal/clickhouse/src/keys/active_keys.ts (3)

290-299: LGTM! New minute-based timeseries functions are properly implemented.

The new exported functions for minute-level granularity are correctly implemented using the timeseries querier factory pattern, consistent with the existing hour, day, and month-based functions.


301-338: Good organizational improvement with granularity comments.

Adding comments to group timeseries functions by granularity type (minute, hour, day, month) improves code readability and organization.


63-78:

Details

✅ Verification successful

Verify the table reference for minute-based intervals.

All minute-based intervals reference "verifications.key_verifications_per_minute_v1" table. Confirm that active keys data should be queried from the verifications table rather than having a dedicated active_keys_per_minute table.


🏁 Script executed:

#!/bin/bash
# Check if there's an active_keys_per_minute table or if active keys data is stored in the verifications table
rg -A 3 "CREATE TABLE.*active_keys.*minute" --glob "*.sql"
rg -A 3 "FROM verifications.key_verifications_per_minute" --glob "*.ts" | grep -v "active_keys.ts"

Length of output: 159


🏁 Script executed:

#!/bin/bash
# Broad search for any SQL table or view related to active keys
rg -n 'active_keys' --glob '*.sql'
rg -n 'active_keys_per_minute' --glob '*.sql'
rg -n 'key_active_keys_per_minute_v1' --glob '*.sql'

# Search references in TS code
rg -n 'active_keys' --glob '*.ts'
rg -n 'active_keys_per_minute' --glob '*.ts'

Length of output: 277


Minute-based intervals use the correct table
I don’t see any active_keys_per_minute table in our SQL definitions, so querying from verifications.key_verifications_per_minute_v1 for all minute-based intervals is appropriate.

internal/clickhouse/src/index.ts (6)

5-11: Import organization looks good.

The addition of import statements for the minute-level granularity functions is well-organized and follows the existing code pattern.


61-67: Import structure is consistent.

The new verification timeseries import statements are properly organized alongside existing imports, maintaining the codebase's style.


121-124: Well-structured minute granularity addition for verification timeseries.

The new minute-based granularity methods are properly implemented in the verifications.timeseries object with a clear comment indicating the granularity level. This follows the PR objective of adding minute-level granularity support.


131-136: Good organization with descriptive comments.

Adding section comments to distinguish between granularity levels improves code readability and maintainability.


139-143: Consistent implementation for active keys timeseries.

The minute-based granularity functions for active keys are implemented consistently with the verification timeseries pattern.


149-154: Consistent organization across the codebase.

The section comments for day-based and month-based granularities maintain the same structure as the added minute-based sections, ensuring consistency throughout the file.

internal/clickhouse/src/verifications.ts (7)

197-212: Well-defined intervals for minute-based granularity.

The addition of minute, five-minute, and thirty-minute intervals is well-structured and consistent with the existing interval definitions. All new intervals correctly reference the new verifications.key_verifications_per_minute_v1 table.


275-277: Appropriate interval unit mapping for minutes.

The interval unit mappings for "MINUTE" and "MINUTES" are correctly set to "minute", consistent with how other units are mapped.


287-289: Correct millisecond conversion for minute intervals.

The millisecond per unit mappings for "MINUTE" and "MINUTES" are properly set to 60,000 (60 seconds * 1000 milliseconds), ensuring accurate time calculations.


509-519: Well-implemented minute-based timeseries functions.

The new minute-based verification timeseries functions are implemented correctly, following the established pattern and using the appropriate interval constants.


520-536: Good organization with descriptive comments.

Adding the "Hour-based timeseries" comment improves code organization and readability, making it clear which functions operate at which time granularity.


537-547: Consistent commenting for day-based timeseries.

The "Day-based timeseries" comment maintains the organizational structure introduced with the minute and hour sections.


548-551: Complete organization with month-based comment.

The "Month-based timeseries" comment finishes the organizational structure, ensuring all granularity levels are clearly labeled.

@chronark
Copy link
Collaborator

could you add a copy of the table schemas here as well please. no downlevel migrations, just the CREATE TABLE IF NOT EXISTS
go/pkg/clickhouse/schema/databases

Copy link
Contributor Author

lemme see

@ogzhanolguncu ogzhanolguncu added this pull request to the merge queue May 14, 2025
Merged via the queue into main with commit 320e6f9 May 14, 2025
33 of 38 checks passed
@ogzhanolguncu ogzhanolguncu deleted the add-minute-granularity-for-verifications branch May 14, 2025 13:06
@coderabbitai coderabbitai bot mentioned this pull request Aug 15, 2025
18 tasks
@coderabbitai coderabbitai bot mentioned this pull request Sep 17, 2025
18 tasks
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