Skip to content
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

Use jemalloc #48

Draft
wants to merge 4 commits into
base: main
Choose a base branch
from
Draft

Use jemalloc #48

wants to merge 4 commits into from

Conversation

lalinsky
Copy link
Member

@lalinsky lalinsky commented Dec 16, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a custom memory allocator using the jemalloc library.
    • Updated memory allocation strategy to utilize the new allocator in optimized builds.
  • Chores

    • Enhanced environment setup by installing libjemalloc-dev and libjemalloc2 packages.
  • Bug Fixes

    • Improved memory management optimizations in the build process.

Copy link

coderabbitai bot commented Dec 18, 2024

Walkthrough

The pull request introduces jemalloc, a high-performance memory allocator, into the project. Changes span multiple files to integrate jemalloc as an alternative memory allocation strategy. The workflow and Dockerfile are updated to install jemalloc dependencies, the build configuration is modified to link the library, and a new jemalloc.zig file implements a custom allocator. The main application's memory allocation strategy is conditionally updated to use jemalloc during release fast builds.

Changes

File Change Summary
.github/workflows/build.yml Added step to install libjemalloc-dev package
Dockerfile Added libjemalloc2 to package installation
build.zig Added linkSystemLibrary("jemalloc") for release fast builds
src/jemalloc.zig New file implementing jemalloc-based memory allocator
src/main.zig Updated allocator selection to use jemalloc in release fast mode

Sequence Diagram

sequenceDiagram
    participant Build as Build System
    participant Main as Main Application
    participant Allocator as Memory Allocator
    
    Build->>Main: Configure Build
    alt Release Fast Mode
        Build->>Main: Link jemalloc
        Main->>Allocator: Use jemalloc Allocator
    else Other Modes
        Main->>Allocator: Use Default Allocator
    end
Loading

Poem

🐰 Jemalloc hops into our code,
With memory swift and memory bold,
Allocating bytes with rabbit-like grace,
Performance leaps at lightning pace,
A memory dance, both nimble and free! 🚀


🪧 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

@lalinsky
Copy link
Member Author

@coderabbitai review

Copy link

coderabbitai bot commented Dec 18, 2024

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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

🧹 Nitpick comments (3)
Dockerfile (1)

3-3: Consider pinning the package version for consistency.

While adding libjemalloc2 is correct, consider pinning its version to ensure consistent builds across environments.

-RUN apt-get update && apt-get install -y glibc-tools libjemalloc2
+RUN apt-get update && apt-get install -y glibc-tools libjemalloc2=5.3.0-2
src/jemalloc.zig (1)

7-14: Initialize the allocator ptr field.

The ptr field is marked as undefined. While this might work since the field isn't used, it's better to initialize it properly for safety and clarity.

 pub const allocator = Allocator{
-    .ptr = undefined,
+    .ptr = null,
     .vtable = &.{
         .alloc = alloc,
         .resize = resize,
         .free = free,
     },
 };
.github/workflows/build.yml (1)

33-34: Consider pinning package version and optimizing installation steps.

For consistency and reproducibility:

  1. Pin the package version
  2. Consider combining this with other apt installation steps if they exist in the workflow
-      - run: sudo apt-get update && sudo apt-get install -y libjemalloc-dev
+      - name: Install build dependencies
+        run: |
+          sudo apt-get update
+          sudo apt-get install -y libjemalloc-dev=5.3.0-2
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bb60cb7 and 819cbfd.

📒 Files selected for processing (5)
  • .github/workflows/build.yml (1 hunks)
  • Dockerfile (1 hunks)
  • build.zig (1 hunks)
  • src/jemalloc.zig (1 hunks)
  • src/main.zig (2 hunks)
🔇 Additional comments (6)
src/jemalloc.zig (3)

16-22: LGTM! Proper alignment and error handling.

The allocation function correctly handles alignment calculation and memory allocation errors.


40-44: LGTM! Clean implementation.

The free function correctly deallocates memory using je_free.


24-38: Verify je_malloc_usable_size behavior across jemalloc versions.

The resize implementation assumes je_malloc_usable_size returns the total allocatable size. This assumption might not hold true across all jemalloc versions and could lead to memory corruption if incorrect.

src/main.zig (2)

10-10: LGTM: Clean import addition

The jemalloc import follows the existing code style and organization.


45-45: Verify jemalloc integration with existing memory management

The conditional allocator assignment looks good. Using jemalloc only in ReleaseFast mode while maintaining GPA for tests is a solid approach that preserves debugging capabilities.

Let's verify the jemalloc integration:

✅ Verification successful

Jemalloc integration is properly implemented and configured

The jemalloc integration is correctly implemented with:

  • Proper allocator interface implementation in src/jemalloc.zig with all required functions (alloc, resize, free)
  • Correct system library linking in build.zig specifically for ReleaseFast mode
  • Appropriate conditional usage in main.zig that switches between jemalloc and GPA based on build mode
  • Memory safety with proper alignment handling and null checks
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify jemalloc integration completeness

# Check if jemalloc.zig exists and contains necessary allocation functions
echo "Checking jemalloc.zig implementation..."
rg -A 5 "pub fn alloc|pub fn free|pub fn realloc" "src/jemalloc.zig"

# Verify no direct c_allocator usage remains
echo "Checking for remaining c_allocator usage..."
rg "c_allocator" --type zig

Length of output: 282


Script:

#!/bin/bash
# Let's first check if jemalloc.zig exists and its content
echo "Checking for jemalloc.zig..."
fd "jemalloc.zig" --type f

echo "\nChecking imports of jemalloc..."
rg "jemalloc" --type zig

# Check memory allocation patterns in the codebase
echo "\nChecking memory allocation patterns..."
rg "allocator\." --type zig -A 2

Length of output: 4905


Script:

#!/bin/bash
# Let's examine the jemalloc.zig implementation
echo "Checking jemalloc.zig content..."
cat src/jemalloc.zig

# Check build configuration for jemalloc
echo "\nChecking build configuration..."
cat build.zig

Length of output: 4632

build.zig (1)

47-47: Verify jemalloc availability in build environments

The jemalloc library linking is correctly configured for ReleaseFast builds and properly placed after linkLibC().

Let's verify the build configuration:

✅ Verification successful

Jemalloc dependency is properly configured across build environments

The verification confirms that jemalloc is correctly set up:

  • GitHub Actions workflow installs libjemalloc-dev package
  • Dockerfile includes libjemalloc2 installation
  • Build system properly handles cross-compilation through standardTargetOptions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify build configuration and dependencies

# Check if workflow file includes jemalloc installation
echo "Checking workflow configuration..."
rg "jemalloc" .github/workflows/

# Check if Dockerfile includes jemalloc
echo "Checking Dockerfile configuration..."
rg "jemalloc" Dockerfile

# Check for cross-compilation configurations
echo "Checking for cross-compilation settings..."
rg "target" build.zig

Length of output: 1003

Comment on lines +46 to +49
test "basic" {
const buf = try allocator.alloc(u8, 256);
defer allocator.free(buf);
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Enhance test coverage with additional test cases.

The current test is basic. Consider adding tests for:

  • Different alignment values
  • Buffer resizing
  • Zero-size allocation
  • Large allocation
  • Out-of-memory conditions
 test "basic" {
     const buf = try allocator.alloc(u8, 256);
     defer allocator.free(buf);
+
+    // Test alignment
+    const aligned_buf = try allocator.alignedAlloc(u8, 16, 256);
+    defer allocator.free(aligned_buf);
+
+    // Test resize
+    const resize_buf = try allocator.alloc(u8, 128);
+    defer allocator.free(resize_buf);
+    try std.testing.expect(allocator.resize(resize_buf, 256));
+
+    // Test zero-size
+    const zero_buf = try allocator.alloc(u8, 0);
+    defer allocator.free(zero_buf);
+
+    // Test large allocation
+    const large_buf = try allocator.alloc(u8, 1 << 20);
+    defer allocator.free(large_buf);
 }

Committable suggestion skipped: line range outside the PR's diff.

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.

1 participant