Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

@BilalG1
Copy link
Contributor

@BilalG1 BilalG1 commented Feb 2, 2026

Summary by CodeRabbit

  • New Features

    • Added a dedicated endpoint to retrieve query timing statistics using query identifiers.
    • Query responses now include a unique query_id for tracking and reference.
  • Improvements

    • Query timeout validation now enforces a maximum limit of 2 minutes.
    • Query response structure updated to support separate timing information retrieval.

@vercel
Copy link

vercel bot commented Feb 2, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
stack-backend Ready Ready Preview, Comment Feb 2, 2026 11:30pm
stack-dashboard Ready Ready Preview, Comment Feb 2, 2026 11:30pm
stack-demo Ready Ready Preview, Comment Feb 2, 2026 11:30pm
stack-docs Ready Ready Preview, Comment Feb 2, 2026 11:30pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 2, 2026

📝 Walkthrough

Walkthrough

This refactoring separates query execution from timing retrieval. The analytics query endpoint now returns a query_id instead of CPU and wall-clock stats. A new /timing endpoint fetches timing statistics using the query_id. Changes include a project-scoped timing helper function, updated response types, and expanded test coverage.

Changes

Cohort / File(s) Summary
API Route — Query Execution
apps/backend/src/app/api/latest/internal/analytics/query/route.ts
Removed timing stats from response. Changed to return composite query_id (tenancy project id + branch id + UUID). Added timeout validation with MAX_QUERY_TIMEOUT_MS (120s) and DEFAULT_QUERY_TIMEOUT_MS (10s) bounds. Removed getQueryTimingStats dependency and related timing fetch logic.
API Route — Timing Retrieval
apps/backend/src/app/api/latest/internal/analytics/query/timing/route.ts
New endpoint that fetches CPU and wall-clock timing stats for a given query_id via ClickHouse. Validates authenticated requests, verifies tenancy-based query_id prefix, and returns timing metrics in milliseconds with structured validation schemas.
Backend Library — ClickHouse Helper
apps/backend/src/lib/clickhouse.tsx
Added getQueryTimingStatsForProject(client, queryId) function to query system.query_log for timing stats. Includes retry mechanism with extended delays [75, 150, 300, 600, 1200, 2400, 4800] ms and returns null if no data found after retries.
Type Definitions
packages/stack-shared/src/interface/crud/analytics.ts, packages/stack-shared/src/interface/admin-interface.ts
Extended AnalyticsQueryResponse with query_id: string field. Updated queryAnalytics to include query_id in returned object alongside result.
E2E Tests — Analytics Events
apps/e2e/tests/backend/endpoints/api/v1/analytics-events.test.ts
Added stripQueryId helper to sanitize and remove dynamic query_id from responses before snapshot comparisons. Removed stats fields from expected snapshots.
E2E Tests — Analytics Query
apps/e2e/tests/backend/endpoints/api/v1/analytics-query.test.ts
Added fetchQueryTiming and fetchQueryTimingWithRetry helpers to poll timing endpoint. Refactored tests with stripQueryId to remove query_id from snapshots. Added new test cases for timing retrieval, project isolation, parameter handling, timeout validation (rejects >2 min), and expanded error scenario coverage (SCHEMA_ERROR, ANALYTICS_QUERY_ERROR).
Dashboard UI — Formatting
apps/dashboard/src/app/(main)/(protected)/projects/[projectId]/analytics/tables/page-client.tsx, apps/dashboard/src/components/commands/run-query.tsx
Cosmetic indentation and import statement reflow in Dialog and Phosphor icon imports. No functional or behavioral changes.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant QueryAPI as Query API<br/>/query
    participant TimingAPI as Timing API<br/>/query/timing
    participant ClickHouse

    rect rgba(200, 150, 100, 0.5)
    Note over Client,ClickHouse: New Flow: Separate Query & Timing
    Client->>QueryAPI: POST with analytics query
    activate QueryAPI
    QueryAPI->>ClickHouse: Execute query
    ClickHouse-->>QueryAPI: Query result
    QueryAPI-->>Client: { result: [...], query_id: "proj_branch_uuid" }
    deactivate QueryAPI
    
    Note over Client,ClickHouse: Client later fetches timing
    Client->>TimingAPI: POST with query_id
    activate TimingAPI
    TimingAPI->>ClickHouse: Query system.query_log
    ClickHouse-->>TimingAPI: Timing stats (cpu_time, wall_clock_time)
    TimingAPI-->>Client: { cpu_time: X, wall_clock_time: Y }
    deactivate TimingAPI
    end

    rect rgba(100, 150, 200, 0.5)
    Note over Client,ClickHouse: Previous Flow: Combined Query & Timing
    Client->>QueryAPI: POST with analytics query
    activate QueryAPI
    QueryAPI->>ClickHouse: Execute & fetch timing stats
    ClickHouse-->>QueryAPI: Result + timing metrics
    QueryAPI-->>Client: { result: [...], stats: { cpu_time, wall_clock_time } }
    deactivate QueryAPI
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • fix analytics queries #1141: Modifies ClickHouse query-timing logic with query-profile wrapper and retry mechanisms in clickhouse.tsx, directly related to the new timing helper introduced here.
  • clickhouse setup #1032: Adds ClickHouse client utilities and analytics query route; this PR refactors that flow by introducing project-scoped timing retrieval and moving stats to a dedicated endpoint.

Poem

🐰 A query hops forth, swift and light,
Returns its ID, shimmering bright,
Timing stats fetch in a separate stride,
Two endpoints now, side by side! 🌟

🚥 Pre-merge checks | ❌ 3
❌ Failed checks (2 warnings, 1 inconclusive)
Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is empty except for a template comment, providing no meaningful information about the changes, motivation, or implementation details. Add a comprehensive description explaining the changes, including the reason for splitting endpoints, how the new query_id is structured, and any migration considerations for clients.
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'query timing route' is vague and overly generic, failing to clearly summarize the main changes in the changeset. Improve the title to be more specific and descriptive, such as 'Split query analytics and timing into separate endpoints' or 'Add dedicated query timing endpoint and update analytics API response structure.'

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch query-timing-route

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@greptile-apps
Copy link
Contributor

greptile-apps bot commented Feb 2, 2026

Greptile Overview

Greptile Summary

Refactored analytics query execution to return query timing statistics via a separate endpoint instead of inline. The /analytics/query endpoint now returns a query_id that can be used to fetch timing stats from the new /analytics/query/timing endpoint.

Key changes:

  • Query IDs now include project and branch identifiers (projectId:branchId:uuid) for authorization
  • New /analytics/query/timing endpoint validates query ownership before returning stats
  • Query timing now uses async polling without blocking the initial query response
  • Maximum query timeout enforced at 2 minutes (120 seconds)
  • Comprehensive test coverage for the new timing endpoint and cross-project security

Confidence Score: 5/5

  • This PR is safe to merge with minimal risk
  • Clean refactoring with proper security validation, comprehensive test coverage, and no breaking changes
  • No files require special attention

Important Files Changed

Filename Overview
apps/backend/src/app/api/latest/internal/analytics/query/route.ts Refactored to return query_id instead of inline stats, added max timeout validation
apps/backend/src/app/api/latest/internal/analytics/query/timing/route.ts New endpoint to fetch query timing stats separately with authorization validation
apps/backend/src/lib/clickhouse.tsx Added getQueryTimingStatsForProject with retry logic and null return instead of throwing

Sequence Diagram

sequenceDiagram
    participant Client
    participant QueryRoute as /analytics/query
    participant TimingRoute as /analytics/query/timing
    participant ClickHouse
    participant QueryLog as system.query_log

    Client->>QueryRoute: POST with query & params
    QueryRoute->>QueryRoute: Generate queryId<br/>(projectId:branchId:uuid)
    QueryRoute->>ClickHouse: Execute query with queryId
    ClickHouse-->>QueryRoute: Query results
    QueryRoute-->>Client: Return results + queryId
    
    Note over QueryLog: ClickHouse logs query<br/>to system.query_log<br/>(async, up to 7.5s delay)
    
    Client->>TimingRoute: POST with queryId
    TimingRoute->>TimingRoute: Validate queryId prefix<br/>(projectId:branchId)
    TimingRoute->>QueryLog: Query timing stats (with retry)
    alt Stats available
        QueryLog-->>TimingRoute: cpu_time_ms, wall_clock_time_ms
        TimingRoute-->>Client: Return stats
    else Stats not found after retries
        TimingRoute-->>Client: 404 Not Found
    end
Loading

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 files reviewed, no comments

Edit Code Review Agent Settings | Greptile

@BilalG1 BilalG1 requested a review from N2D4 February 2, 2026 18:50
@BilalG1 BilalG1 assigned N2D4 and unassigned BilalG1 Feb 2, 2026
@BilalG1 BilalG1 merged commit 31b8d80 into dev Feb 3, 2026
27 checks passed
@BilalG1 BilalG1 deleted the query-timing-route branch February 3, 2026 00:08
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.

3 participants