Skip to content

Conversation

@nischitpra
Copy link
Collaborator

@nischitpra nischitpra commented Aug 16, 2025

Summary by CodeRabbit

  • New Features

    • Added per-storage ClickHouse max memory usage setting (default 1 GB) for orchestrator, main, and staging storages. Configurable via CLI flags and configuration.
  • Refactor

    • Consolidated ClickHouse query settings so multiple options (e.g., execution timeout and memory limit) are applied together for more consistent behavior.

@zeet-co
Copy link

zeet-co bot commented Aug 16, 2025

We're building your pull request over on Zeet.
Click me for more info about your build and deployment.
Once built, this branch can be tested at: https://abstract-testnet-indexer-hme8-np--4a7c60.insight-prod-gke.zeet.app before merging 😉

@coderabbitai
Copy link

coderabbitai bot commented Aug 16, 2025

Walkthrough

Added maxMemoryUsage support for ClickHouse across CLI flags, Viper bindings, and configuration struct. Updated query assembly to aggregate ClickHouse SETTINGS (max_execution_time, max_memory_usage) into a single clause appended at the end, only when applicable.

Changes

Cohort / File(s) Summary
CLI Flags & Viper Bindings
cmd/root.go
Introduced three persistent flags for ClickHouse maxMemoryUsage (orchestrator, main, staging), default 1e9. Bound to Viper keys: storage.orchestrator.clickhouse.maxMemoryUsage, storage.main.clickhouse.maxMemoryUsage, storage.staging.clickhouse.maxMemoryUsage.
Config Model
configs/config.go
Added ClickhouseConfig field: MaxMemoryUsage int mapstructure:"maxMemoryUsage" to support unmarshalling.
ClickHouse Query Settings Assembly
internal/storage/clickhouse.go
Refactored addPostQueryClauses to collect applicable settings and append a single SETTINGS clause at end. Supports max_memory_usage alongside max_execution_time; joins multiple settings with commas and omits clause when none present.

Sequence Diagram(s)

sequenceDiagram
    participant CLI as CLI Flags
    participant Viper as Viper Config
    participant Config as Config Loader
    participant CH as ClickHouse Query Builder
    participant DB as ClickHouse

    CLI->>Viper: Define flags (maxMemoryUsage per scope)
    Viper->>Config: Unmarshal into ClickhouseConfig (MaxMemoryUsage)
    Config->>CH: Provide config values
    CH->>CH: Build query body
    CH->>CH: addPostQueryClauses(settings: max_execution_time, max_memory_usage)
    CH->>DB: Execute query with single SETTINGS clause (if any)
    DB-->>CH: Results
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch np/max_memory_limit

🪧 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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@nischitpra nischitpra merged commit 3a03423 into main Aug 16, 2025
4 of 5 checks passed
@nischitpra nischitpra deleted the np/max_memory_limit branch August 16, 2025 20:48
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

🧹 Nitpick comments (3)
configs/config.go (1)

88-88: Consider using uint64 for memory values to avoid overflow on 32-bit systems

While 1e9 fits within int, memory limits can exceed 2 GiB in some deployments. Using uint64 provides safer headroom for large byte values.

Apply this minimal change:

-   MaxMemoryUsage               int                            `mapstructure:"maxMemoryUsage"`
+   MaxMemoryUsage               uint64                         `mapstructure:"maxMemoryUsage"`
internal/storage/clickhouse.go (1)

673-684: Optional: add a small unit test to lock query shape with both settings present

Given you already expose TestQueryGeneration, a focused test will prevent regressions in clause ordering.

Example test (new file: internal/storage/clickhouse_query_test.go):

package storage

import (
	"math/big"
	"testing"

	config "github.com/thirdweb-dev/indexer/configs"
)

func TestBuildQuery_AppendsSettingsOnce(t *testing.T) {
	cfg := &config.ClickhouseConfig{
		Database:      "db",
		MaxQueryTime:  30,
		MaxMemoryUsage: 1_000_000_000,
	}
	c, err := NewClickHouseConnector(cfg)
	if err != nil {
		t.Fatalf("connector init: %v", err)
	}

	q := c.TestQueryGeneration("blocks", "block_number", QueryFilter{
		ChainId: big.NewInt(1),
		Limit:   10,
	})
	want := "SETTINGS max_execution_time = 30, max_memory_usage = 1000000000"
	if count := len(regexp.MustCompile(`\bSETTINGS\b`).FindAllStringIndex(q, -1)); count != 1 {
		t.Fatalf("expected one SETTINGS clause, got %d in %q", count, q)
	}
	if !strings.Contains(q, want) {
		t.Fatalf("missing expected SETTINGS: %q in query: %q", want, q)
	}
}

Happy to add this in a follow-up PR if helpful.

cmd/root.go (1)

87-87: Optional: widen type to Uint64 for large memory limits

If you anticipate values >2 GiB, prefer Uint64 flags and a uint64 field in config. This prevents overflow on 32-bit systems and communicates the domain more clearly.

Suggested changes to flag declarations:

- rootCmd.PersistentFlags().Int("storage-orchestrator-clickhouse-maxMemoryUsage", 1000000000, "Clickhouse max memory usage in bytes for orchestrator storage")
+ rootCmd.PersistentFlags().Uint64("storage-orchestrator-clickhouse-maxMemoryUsage", 1_000_000_000, "Clickhouse max memory usage in bytes for orchestrator storage")

- rootCmd.PersistentFlags().Int("storage-main-clickhouse-maxMemoryUsage", 1000000000, "Clickhouse max memory usage in bytes for main storage")
+ rootCmd.PersistentFlags().Uint64("storage-main-clickhouse-maxMemoryUsage", 1_000_000_000, "Clickhouse max memory usage in bytes for main storage")

- rootCmd.PersistentFlags().Int("storage-staging-clickhouse-maxMemoryUsage", 1000000000, "Clickhouse max memory usage in bytes for staging storage")
+ rootCmd.PersistentFlags().Uint64("storage-staging-clickhouse-maxMemoryUsage", 1_000_000_000, "Clickhouse max memory usage in bytes for staging storage")

And pair with changing ClickhouseConfig.MaxMemoryUsage to uint64 as suggested in configs/config.go.

Also applies to: 109-109, 119-119, 202-202, 215-215, 228-228

📜 Review details

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

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9ca9e74 and 1a3ef92.

📒 Files selected for processing (3)
  • cmd/root.go (6 hunks)
  • configs/config.go (1 hunks)
  • internal/storage/clickhouse.go (1 hunks)
🔇 Additional comments (5)
configs/config.go (1)

88-88: LGTM: Config supports ClickHouse maxMemoryUsage

The new MaxMemoryUsage field and mapstructure tag align with the new flags and Viper bindings. Unmarshalling should work as expected.

internal/storage/clickhouse.go (2)

673-684: LGTM: Aggregate ClickHouse SETTINGS and append once at the end

Collecting applicable settings into a single SETTINGS clause is cleaner and avoids multiple scattered clauses. The conditional emission and comma-join are correct.


673-684: No duplicate SETTINGS clauses found
Verified that the only places emitting SETTINGS in query strings are:

  • The performance‐tuning snippet at internal/storage/clickhouse.go:673–684
  • The consistency query in getMaxBlockNumberConsistent at internal/storage/clickhouse.go:898
    The addPostQueryClauses path does not append any SETTINGS.
cmd/root.go (2)

87-87: LGTM: Flags and Viper bindings for maxMemoryUsage are consistent and correctly named

  • Flags: storage-*-clickhouse-maxMemoryUsage with sensible default and clear “bytes” description.
  • Bindings: storage.*.clickhouse.maxMemoryUsage keys match mapstructure tags and config field.

Also applies to: 109-109, 119-119, 202-202, 215-215, 228-228


87-87: Verify default behavior: do we want a non-zero default overriding server-side settings?

Setting 1e9 by default will force a memory cap even when users don't set anything. Consider defaulting to 0 (unset) to inherit ClickHouse server defaults, unless product requirements dictate otherwise.

Would you like me to open a follow-up to switch the defaults to 0 and document the behavior?

Also applies to: 109-109, 119-119

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