Skip to content

⚡ Bolt: [performance improvement] Remove intermediate String allocations - #9

Merged
SayanthRock merged 1 commit into
mainfrom
bolt-optimize-allocations-3031974126509498206
Aug 12, 2026
Merged

⚡ Bolt: [performance improvement] Remove intermediate String allocations#9
SayanthRock merged 1 commit into
mainfrom
bolt-optimize-allocations-3031974126509498206

Conversation

@SayanthRock

@SayanthRock SayanthRock commented Aug 10, 2026

Copy link
Copy Markdown
Member

User description

💡 What:

  • Optimized compiler/rockql-sql/src/lib.rs to use eq_ignore_ascii_case() instead of creating a lowercase String clone to check for string targets.
  • Optimized compiler/rockql-parser/src/lib.rs by parsing a numerical string manually by iterating its bytes instead of replacing character subsets and parsing using standard libraries which allocates an intermediate String.

🎯 Why:

  • These loops happen frequently when checking language targets and in compiler paths for extracting parameters.
  • Re-allocating Strings to execute comparison checks puts needless pressure on the memory allocator resulting in poor cache locality and performance drops.

📊 Impact:

  • Zero allocations to verify and identify SQL output targets.
  • Zero allocations to parse u64 numerical parameters.
  • Reduced GC-like pressure on allocator and heap.

🔬 Measurement:

  • Check cache grind hits using micro-benchmarks or track heap allocations on large AST inputs.

PR created automatically by Jules for task 3031974126509498206 started by @SayanthRock


CodeAnt-AI Description

Reduce compiler overhead when parsing SQL targets and row limits

What Changed

  • SQL dialect names are recognized without creating temporary lowercase strings
  • take row counts are parsed directly, including values containing underscores, without creating an intermediate string
  • Invalid, empty, non-numeric, and overflowing row counts continue to produce a clear error

Impact

✅ Lower memory use during query compilation
✅ Faster repeated dialect and row-count parsing
✅ Clear errors for invalid row limits

💡 Usage Guide

Checking Your Pull Request

Every time you make a pull request, our system automatically looks through it. We check for security issues, mistakes in how you're setting up your infrastructure, and common code problems. We do this to make sure your changes are solid and won't cause any trouble later.

Talking to CodeAnt AI

Got a question or need a hand with something in your pull request? You can easily get in touch with CodeAnt AI right here. Just type the following in a comment on your pull request, and replace "Your question here" with whatever you want to ask:

@codeant-ai ask: Your question here

This lets you have a chat with CodeAnt AI about your pull request, making it easier to understand and improve your code.

Example

@codeant-ai ask: Can you suggest a safer alternative to storing this secret?

Preserve Org Learnings with CodeAnt

You can record team preferences so CodeAnt AI applies them in future reviews. Reply directly to the specific CodeAnt AI suggestion (in the same thread) and replace "Your feedback here" with your input:

@codeant-ai: Your feedback here

This helps CodeAnt AI learn and adapt to your team's coding style and standards.

Example

@codeant-ai: Do not flag unused imports.

Retrigger review

Ask CodeAnt AI to review the PR again, by typing:

@codeant-ai: review

Check Your Repository Health

To analyze the health of your code repository, visit our dashboard at https://app.codeant.ai. This tool helps you identify potential issues and areas for improvement in your codebase, ensuring your repository maintains high standards of code health.

Summary by CodeRabbit

  • Performance

    • Improved query parsing efficiency for row counts, including large values and underscore-separated numbers.
    • Reduced unnecessary string allocation when recognizing SQL dialect names.
  • Bug Fixes

    • Preserved validation for invalid, empty, negative, and overflowing row counts.
    • Maintained case-insensitive support for existing SQL dialect names and aliases.

- Replaced `.to_ascii_lowercase()` with `eq_ignore_ascii_case()` in `Dialect::from_str`.
- Replaced `.replace('_', "")` and `.parse::<u64>()` with manual iteration over bytes in `parse_take` to eliminate intermediate String allocation.

Co-authored-by: SayanthRock <202829406+SayanthRock@users.noreply.github.com>
Copilot AI lite review requested due to automatic review settings August 10, 2026 21:42
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@codeant-ai

codeant-ai Bot commented Aug 10, 2026

Copy link
Copy Markdown

🤖 CodeAnt AI — Review Status

Status Commit Started (UTC) Finished (UTC)
✅ Reviewed your PR 3d02d59 Aug 10, 2026 · 21:42 21:43

@codeant-ai

codeant-ai Bot commented Aug 10, 2026

Copy link
Copy Markdown

Thanks for using CodeAnt! 🎉

We're free for open-source projects. if you're enjoying it, help us grow by sharing.

Share on X ·
Reddit ·
LinkedIn

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@codeant-ai codeant-ai Bot added the size:M This PR changes 30-99 lines, ignoring generated files label Aug 10, 2026

@ai-coding-guardrails ai-coding-guardrails Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Nice work! 😎

I didn't find anything of concern

Risk: 🟢 Low

Risk analysis

The highest scoring dimensions are blast_radius and test_coverage. The changes affect core compiler logic in rockql-sql and rockql-parser which may be used across multiple services, giving it a moderate blast radius. The manual parsing logic in rockql-parser introduces new code paths without explicit mention of updated tests, lowering confidence in coverage. Other dimensions score low as there are no apparent security, data integrity, or major operational risks introduced by these performance optimizations.

Reviewed with 🤟 by Zenable

@coderabbitai

coderabbitai Bot commented Aug 10, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The parser now avoids intermediate string allocation when parsing TAKE counts and SQL dialect names. Existing aliases, validation rules, overflow handling, and error behavior remain unchanged.

Changes

Parsing efficiency

Layer / File(s) Summary
Manual TAKE count parsing
compiler/rockql-parser/src/lib.rs
parse_take parses counts byte by byte, skips underscores, rejects invalid input, and reports u64 overflow.
Case-insensitive dialect parsing
compiler/rockql-sql/src/lib.rs
Dialect::from_str uses eq_ignore_ascii_case for supported aliases without allocating a lowercase string.

Estimated code review effort: 2 (Simple) | ~10 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly describes the pull request's main change: removing intermediate String allocations to improve performance.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch bolt-optimize-allocations-3031974126509498206

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.

@ai-coding-guardrails ai-coding-guardrails Bot added the zenable/risk:low Zenable assessed this PR as LOW risk. label Aug 10, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@compiler/rockql-parser/src/lib.rs`:
- Around line 221-238: The numeric parsing loop in the take row-count handling
must continue accepting a single leading plus sign. Update the logic around the
visible byte iteration so `+10` and `+_10` are valid, while preserving
underscore skipping, digit validation, and rejection of plus signs elsewhere;
add regression tests covering both forms.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 26f03dae-9faf-4423-82f5-1633850c001e

📥 Commits

Reviewing files that changed from the base of the PR and between f2c322f and 3d02d59.

📒 Files selected for processing (2)
  • compiler/rockql-parser/src/lib.rs
  • compiler/rockql-sql/src/lib.rs

Comment on lines +221 to +238
for &byte in rest.as_bytes() {
if byte == b'_' {
continue;
} else if byte.is_ascii_digit() {
has_digits = true;
let digit = (byte - b'0') as u64;
count = count
.checked_mul(10)
.and_then(|c| c.checked_add(digit))
.ok_or_else(|| {
Diagnostic::new("`take` requires a non-negative integer row count", span)
})?;
} else {
return Err(Diagnostic::new(
"`take` requires a non-negative integer row count",
span,
));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

if ! rg -n -P 'take\s+\+[_0-9]+' compiler/rockql-parser --glob '*.rs'; then
  echo "Missing regression coverage for plus-prefixed TAKE counts." >&2
  exit 1
fi

Repository: Sayanthrock-Developer/ROCKQL

Length of output: 225


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf '%s\n' '--- parser source ---'
sed -n '180,270p' compiler/rockql-parser/src/lib.rs

printf '%s\n' '--- TAKE-related tests and implementations ---'
rg -n -C 4 'take|TAKE|from_str|parse::<u64>' compiler/rockql-parser --glob '*.rs'

printf '%s\n' '--- repository status ---'
git diff --stat
git status --short

Repository: Sayanthrock-Developer/ROCKQL

Length of output: 7932


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

printf '%s\n' '--- recent commits ---'
git log --oneline -5

printf '%s\n' '--- command parsing around TAKE dispatch ---'
sed -n '60,135p' compiler/rockql-parser/src/lib.rs

printf '%s\n' '--- prior parse_take implementation ---'
parent="$(git rev-parse HEAD^)"
git show "$parent:compiler/rockql-parser/src/lib.rs" | sed -n '205,255p'

printf '%s\n' '--- current and prior parse_take diffs ---'
git diff "$parent" HEAD -- compiler/rockql-parser/src/lib.rs | sed -n '/parse_take/,$p'

Repository: Sayanthrock-Developer/ROCKQL

Length of output: 5738


🌐 Web query:

Rust u64 FromStr leading plus sign underscores syntax "+_10"

💡 Result:

In Rust, the standard library's FromStr implementation for unsigned integer types like u64 does not support leading plus signs (+) or underscores (_) in input strings [1][2]. When you attempt to parse such strings, the operation will return an Err (specifically ParseIntError with kind: InvalidDigit) [1][2]. 1. Leading Plus Sign: While some other programming languages permit a leading + sign for positive integers, Rust's str::parse::<u64>() and u64::from_str() are strictly defined to reject them [1][3][2]. To handle strings that might contain a leading +, you must explicitly remove it before parsing, for example by using s.trim_start_matches('+').parse::<u64>() [1]. 2. Underscores: Similarly, FromStr does not support underscores (e.g., 1_000) within the string [4]. If your input data contains underscores, you must strip them before calling parse() [4]. A common approach is to use s.replace('_', "").parse::<u64>() [4]. These behaviors are intentional design choices in Rust's standard library to maintain strict, predictable parsing rules [1][2]. Top Results: [1], [3], [2], [4]

Citations:


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

if ! command -v rustc >/dev/null 2>&1; then
  echo "rustc is unavailable"
  exit 0
fi

rustc --edition=2021 -o /tmp/rockql_u64_probe - <<'RS'
fn main() {
    for input in ["+10", "+_10", "10", "1_0", "_10", "10_"] {
        let old = input.replace('_', "").parse::<u64>().ok();
        println!("{input:?}: old_parse={old:?}");
    }
}
RS

/tmp/rockql_u64_probe

Repository: Sayanthrock-Developer/ROCKQL

Length of output: 322


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

rustc --edition=2021 -o /tmp/rockql_take_compat_probe - <<'RS'
fn old(input: &str) -> bool {
    input.replace('_', "").parse::<u64>().is_ok()
}

fn current(input: &str) -> bool {
    let mut count = 0u64;
    let mut has_digits = false;

    for &byte in input.as_bytes() {
        if byte == b'_' {
            continue;
        } else if byte.is_ascii_digit() {
            has_digits = true;
            let digit = (byte - b'0') as u64;
            count = match count.checked_mul(10).and_then(|c| c.checked_add(digit)) {
                Some(value) => value,
                None => return false,
            };
        } else {
            return false;
        }
    }

    has_digits
}

fn proposed(input: &str) -> bool {
    let mut count = 0u64;
    let mut has_digits = false;
    let mut has_plus = false;

    for &byte in input.as_bytes() {
        if byte == b'_' {
            continue;
        } else if byte == b'+' && !has_plus && !has_digits {
            has_plus = true;
        } else if byte.is_ascii_digit() {
            has_digits = true;
            let digit = (byte - b'0') as u64;
            count = match count.checked_mul(10).and_then(|c| c.checked_add(digit)) {
                Some(value) => value,
                None => return false,
            };
        } else {
            return false;
        }
    }

    has_digits
}

fn main() {
    let inputs = [
        "+10", "+_10", "_+_10", "++10", "10+", "_", "+", "10", "1_0",
        "_10", "10_", "1__0", "18446744073709551615",
        "18446744073709551616",
    ];

    for input in inputs {
        println!(
            "{input:?}: old={} current={} proposed={}",
            old(input),
            current(input),
            proposed(input)
        );
    }
}
RS

/tmp/rockql_take_compat_probe

Repository: Sayanthrock-Developer/ROCKQL

Length of output: 820


Preserve the existing + sign behavior.

The previous implementation accepted take +10 and take +_10. The current loop rejects b'+'. Allow one leading + before the first digit, after any skipped underscores. Add regression tests for +10 and +_10.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@compiler/rockql-parser/src/lib.rs` around lines 221 - 238, The numeric
parsing loop in the take row-count handling must continue accepting a single
leading plus sign. Update the logic around the visible byte iteration so `+10`
and `+_10` are valid, while preserving underscore skipping, digit validation,
and rejection of plus signs elsewhere; add regression tests covering both forms.

Source: MCP tools

@SayanthRock
SayanthRock merged commit 7339397 into main Aug 12, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size:M This PR changes 30-99 lines, ignoring generated files zenable/risk:low Zenable assessed this PR as LOW risk.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants