Skip to content

Clickhouse performance improvements #2175

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

Merged
merged 5 commits into from
Jun 14, 2025
Merged

Conversation

matt-aitken
Copy link
Member

  • Add organizationId and projectId filtering, to improve CH performance
  • Show the run ID in the Runs table now instead of run number
  • Runs ClickHouse view fix for pagination after going backwards then forward again

Copy link

changeset-bot bot commented Jun 13, 2025

⚠️ No Changeset found

Latest commit: 382a71c

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.

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

Copy link
Contributor

coderabbitai bot commented Jun 13, 2025

Walkthrough

This set of changes introduces organization-level and project-level scoping to several data access and presentation layers of the application. The repository interfaces, implementations, and ClickHouse query parameter schemas for task activity, running stats, and average durations are updated to require organizationId and projectId parameters, and their corresponding SQL queries include these filters. The RunsRepository and its tests now require organizationId for all run queries, and pagination logic is refined for correctness. Presenters and route loaders are updated to pass the new parameters. Additionally, the UI for displaying run IDs is enhanced with tooltip and copyable functionality, and the CopyableText component supports copying a value different from the displayed text.

✨ 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.

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: 3

🔭 Outside diff range comments (2)
apps/webapp/test/runsRepository.test.ts (1)

64-66: 🛠️ Refactor suggestion

Avoid hard-coded setTimeout(1000) in every test – slows CI by ~15 s.

Replace with a polling helper that waits until ClickHouse replication catches up or a max timeout elapses:

async function waitForReplication(ch: ClickHouse, maxMs = 10000) {
  const start = Date.now();
  while (true) {
    const { data } = await ch.query({ query: "SELECT count() FROM system.mutations" });
    if (Number(data[0]?.count) === 0) break;
    if (Date.now() - start > maxMs) throw new Error("Replication timed out");
    await new Promise(r => setTimeout(r, 100));
  }
}

This keeps tests fast while still being deterministic.

apps/webapp/app/services/environmentMetricsRepository.server.ts (1)

55-63: ⚠️ Potential issue

Postgrest implementation no longer satisfies the interface – will not compile

PostgrestEnvironmentMetricsRepository methods still accept only { environmentId, days, tasks }, but the interface now requires { organizationId, projectId, … }.

TypeScript complains:
“Property ‘organizationId’ is missing in type …”.

Besides compilation, the Postgrest queries are now un-scoped by organisation/project, returning cross-tenant data.

Fix (apply to all three methods):

-  public async getDailyTaskActivity({
-    environmentId,
-    days,
-    tasks,
-  }: {
-    environmentId: string;
-    days: number;
-    tasks: string[];
-  }): Promise<DailyTaskActivity> {
+  public async getDailyTaskActivity({
+    organizationId: _orgId,      // presently unused
+    projectId: _projId,          // presently unused
+    environmentId,
+    days,
+    tasks,
+  }: {
+    organizationId: string;
+    projectId: string;
+    environmentId: string;
+    days: number;
+    tasks: string[];
+  }): Promise<DailyTaskActivity> {

Either scope the SQL by these IDs or prefix the unused vars with _ so lint doesn’t complain. Repeat for getCurrentRunningStats and getAverageDurations.

Also applies to: 99-107, 142-150

🧹 Nitpick comments (4)
apps/webapp/app/components/primitives/CopyableText.tsx (1)

7-18: Expose copy-value prop but mind accessibility / event bubbling

Nice addition – separating copyValue from the rendered value covers the truncated-ID use-case.
A couple of small follow-ups will make the component more robust:

  1. The clickable element is a plain <span>, so screen-readers and keyboard users don’t know it’s actionable.
  2. Only onMouseDown stops propagation; a click still bubbles, which could trigger parent navigation (e.g. inside a link-cell).
-      <span
-        onClick={copy}
-        onMouseDown={(e) => e.stopPropagation()}
+      <span
+        role="button"
+        tabIndex={0}
+        aria-label="Copy to clipboard"
+        onClick={(e) => {
+          e.stopPropagation();   // prevent outer link navigation
+          copy();
+        }}
+        onKeyDown={(e) => (e.key === "Enter" || e.key === " ") && copy()}
         className={cn(

This preserves the existing behaviour while improving a11y and eliminating the accidental navigation gotcha.

apps/webapp/app/presenters/v3/NextRunListPresenter.server.ts (2)

48-69: Missing JSDoc & param description for new organizationId.

A short comment would help future maintainers understand why this sits outside RunListOptions, especially now that most other identifiers live in the options object.

   public async call(
-    organizationId: string,
+    /**
+     * Org the request is scoped to – enforced at ClickHouse layer.
+     */
+    organizationId: string,
     environmentId: string,

188-210: Variable naming mismatch (runIds vs runFriendlyIds) causes cognitive load.

runIds coming from the client contains friendly IDs, yet it’s mapped to runFriendlyIds here while the real DB IDs are held in restrictToRunIds. Consider renaming the option to avoid confusion.

-      runFriendlyIds: runIds,
-      runIds: restrictToRunIds,
+      runFriendlyIds: runFriendlyIds, // array of `friendlyId`
+      runIds: restrictToRunIds,       // array of primary-key IDs

(Propagate the rename through the loader & URL param to keep everything aligned.)

internal-packages/clickhouse/src/taskRuns.ts (1)

133-136: Consider composite index / ORDER BY to keep new filters performant.

Filtering by organization_id AND project_id AND environment_id on large tables can become expensive if the primary key / ORDER BY tuple hasn’t been extended accordingly.
Verify the ClickHouse table definition includes these columns at the front of its ORDER BY (or a supporting materialised view) to avoid full-table scans.

Also applies to: 178-183, 219-222

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8a5e7f3 and 382a71c.

📒 Files selected for processing (10)
  • apps/webapp/app/components/primitives/CopyableText.tsx (1 hunks)
  • apps/webapp/app/components/runs/v3/TaskRunsTable.tsx (3 hunks)
  • apps/webapp/app/presenters/v3/NextRunListPresenter.server.ts (2 hunks)
  • apps/webapp/app/presenters/v3/TaskListPresenter.server.ts (3 hunks)
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam._index/route.tsx (1 hunks)
  • apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.next.runs._index/route.tsx (1 hunks)
  • apps/webapp/app/services/environmentMetricsRepository.server.ts (7 hunks)
  • apps/webapp/app/services/runsRepository.server.ts (5 hunks)
  • apps/webapp/test/runsRepository.test.ts (16 hunks)
  • internal-packages/clickhouse/src/taskRuns.ts (6 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/webapp/app/services/runsRepository.server.ts (2)
internal-packages/clickhouse/src/client/noop.ts (1)
  • queryBuilder (14-22)
internal-packages/clickhouse/src/client/client.ts (1)
  • queryBuilder (218-229)
⏰ Context from checks skipped due to timeout of 90000ms (25)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (7, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (2, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (5, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (4, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (8, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (10, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (3, 8)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (6, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (5, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (8, 10)
  • GitHub Check: units / internal / 🧪 Unit Tests: Internal (1, 8)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (9, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (7, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (3, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (4, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (6, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (1, 10)
  • GitHub Check: units / webapp / 🧪 Unit Tests: Webapp (2, 10)
  • GitHub Check: units / packages / 🧪 Unit Tests: Packages (1, 1)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - npm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (ubuntu-latest - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (windows-latest - npm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (8)
apps/webapp/app/components/runs/v3/TaskRunsTable.tsx (2)

55-56: Import of CopyableText looks good

The new component import is correct and keeps run-ID presentation concerns local to the table.


139-139: Header rename clarifies intent

Renaming “Run #” to “ID” matches the new truncated-ID display and is clearer for users.

apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.next.runs._index/route.tsx (1)

130-132: New organizationId argument wired correctly.

The additional parameter is passed in the expected order and type. 👍

apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam._index/route.tsx (1)

128-132: Loader now provides organizationId and projectId.

Signature alignment looks good and keeps the presenter contract consistent.
No further action needed.

internal-packages/clickhouse/src/taskRuns.ts (1)

115-121: Good: schemas updated to require organizationId & projectId.

Explicit scoping is essential for multi-tenant isolation – nice catch.

apps/webapp/app/presenters/v3/TaskListPresenter.server.ts (1)

35-44: All good – parameters correctly propagated

The new organizationId / projectId fields are wired through cleanly and typed; nothing else to address here.

apps/webapp/app/services/runsRepository.server.ts (2)

46-55: 👍 Added tenant scoping

Filtering on organization_id, project_id, and environment_id at the top of the query is clear and indexed-friendly.


118-130: Cursor predicate inconsistent with new composite ordering

Rows are ordered by created_at, run_id but the pagination predicate only compares run_id.
If two runs share the same created_at, items with a smaller run_id but a later timestamp than the cursor can be skipped or duplicated across pages.

To make the ordering and predicate compatible, consider encoding a composite cursor (created_at, run_id):

.where("(created_at, run_id) < ({createdAt: DateTime64}, {runId: String})", {
  createdAt: cursorCreatedAt,
  runId: cursorRunId,
})
.orderBy("created_at DESC, run_id DESC")

Same adjustment needed for the backward branch.

@matt-aitken matt-aitken merged commit a0815c8 into main Jun 14, 2025
33 checks passed
@matt-aitken matt-aitken deleted the clickhouse-perf-improvements branch June 14, 2025 10:10
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