Skip to content

Improved Gitlab All in case of many repositories #372

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

abraverm
Copy link

@abraverm abraverm commented Jul 2, 2025

When there are many repositories on Giltab, doing actions in one hit would fail to API timeout.
This is a quick workaround/hack by using batches.

Also when there a lot of repositories, just getting the list of them might be too much.

Ideally, I would like Sourcebot to add a repository as it finds it instead of handling the entire connection sync. Otherwise this process blocks other connections from syncing, and if it fails/breaks, then it has to start over.

Note: prisma also failing when there are too many connections, not sure what is the magical number is (sometimes 1000 resulted with errors too):

Invalid `prisma.userToOrg.findUnique()` invocation: Too many database connections opened: FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute Prisma Accelerate has built-in connection pooling to prevent such errors: https:/ / pris. ly/ client/ error-accelerate
( https://pris.ly/client/error-accelerate ) at Vn.handleRequestError
(/nix/store/sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/node_modules/@prisma/client/runtime/library.js:121:7339) at Vn.handleAndLogRequestError
(/nix/store/sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/node_modules/@prisma/client/runtime/library.js:121:6663) at Vn.request
(/nix/store/sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/node_modules/@prisma/client/runtime/library.js:121:6370) at async l
(/nix/store/sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/node_modules/@prisma/client/runtime/library.js:130:9617) at async el (/ nix/ store/ sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/ packages/ web/. next/ server/ chunks/ 616. js:1:39994 (
http://nix/store/sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/packages/web/.next/server/chunks/616.js:1:39994
) ) at async ei (/ nix/ store/ sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/ packages/ web/. next/ server/ chunks/ 616. js:1:38467 ( http://nix/store/sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/packages/web/.next/server/chunks/616.js:1:38467
) ) at async j (/ nix/ store/ sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/ packages/ web/. next/ server/ app/ [domain]/ page. js:1:4267 ( http://nix/store/sbwsr0wj0665xvgzg2iqim0c2qdynqkw-sourcebot/packages/web/.next/server/app/[domain]/page.js:1:4267
) ) { code: 'P2037',
clientVersion: '6.2.1',
meta: {
modelName: 'UserToOrg',
message: 'FATAL: remaining connection slots are reserved for roles with the SUPERUSER attribute'
}
}

Summary by CodeRabbit

  • Refactor
    • Improved efficiency and reliability of repository processing by introducing batching for GitLab repository fetches, repository indexing scheduling, and updating repository indexing status.
    • Enhanced logging for better visibility into batch processing progress and outcomes.
  • Bug Fixes
    • Improved error handling for group and user project fetches, ensuring graceful handling of not found errors.
  • Chores
    • Minor code cleanup and improved control flow for repository operations.

Copy link

coderabbitai bot commented Jul 2, 2025

Walkthrough

The changes introduce batching to various operations that previously processed large arrays all at once. GitLab repository fetching, scheduling of repository indexing, and database updates for repository indexing status are now performed in sequential or chunked batches. These modifications affect internal control flow but do not alter any exported function or class signatures.

Changes

File(s) Change Summary
packages/backend/src/gitlab.ts Refactored repository fetching to process groups and users in sequential batches of 10; replaced direct all-projects fetch with separate group/user enumeration; added debug logging and adjusted error handling.
packages/backend/src/repoManager.ts Modified scheduling of repo indexing to process repositories in batches of 100 instead of all at once.
packages/web/src/actions.ts Updated flagReposForIndex to batch update repo indexing status in chunks of 1000 IDs per call.
packages/web/src/initialize.ts Changed retry logic for failed indexing to batch updates in chunks of 100 IDs per call.

Sequence Diagram(s)

sequenceDiagram
    participant Caller
    participant GitLabManager
    participant GitLabAPI

    Caller->>GitLabManager: getGitLabReposFromConfig(config)
    GitLabManager->>GitLabAPI: fetch all groups (batched, size=10)
    GitLabManager->>GitLabAPI: fetch all users (batched, size=10)
    loop For each group batch
        GitLabManager->>GitLabAPI: fetch group projects (batch)
    end
    loop For each user batch
        GitLabManager->>GitLabAPI: fetch user projects (batch)
    end
    GitLabManager-->>Caller: return repositories
Loading
sequenceDiagram
    participant RepoManager
    participant Scheduler

    RepoManager->>RepoManager: fetchAndScheduleRepoIndexing(repos)
    loop For each batch of 100 repos
        RepoManager->>Scheduler: scheduleRepoIndexingBulk(batch)
    end
Loading
sequenceDiagram
    participant Action
    participant Prisma

    Action->>Action: flagReposForIndex(repoIds)
    loop For each batch of 1000 IDs
        Action->>Prisma: updateMany(batch, status=NEW)
    end
Loading
sequenceDiagram
    participant Initializer
    participant Prisma

    Initializer->>Initializer: syncConnections()
    loop For each batch of 100 failed repo IDs
        Initializer->>Prisma: updateMany(batch, status=NEW)
    end
Loading

Poem

In batches now, the work proceeds,
Ten by ten, or hundred seeds.
Repos fetched and status set,
No more giant calls to fret!
Rabbits cheer with nimble hops,
As chunked requests avoid the stops.
🐇✨ Batch by batch, the progress leads!

✨ 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

@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 (5)
packages/web/src/actions.ts (1)

923-933: Good implementation of batching to prevent timeouts.

The sequential batching approach effectively addresses the API timeout issues mentioned in the PR objectives. The chunk size of 1000 is reasonable for database operations.

Consider adding error handling to ensure partial failures don't leave the system in an inconsistent state:

 for (let i = 0; i < repoIds.length; i += 1000) {
+    try {
         await prisma.repo.updateMany({
             where: {
                 id: { in: repoIds.slice(i, i + 1000) },
                 orgId: org.id,
             },
             data: {
                 repoIndexingStatus: RepoIndexingStatus.NEW,
             }
         });
+    } catch (error) {
+        logger.error(`Failed to update batch ${i / 1000 + 1}: ${error}`);
+        throw error; // Re-throw to maintain existing error handling behavior
+    }
 }
packages/web/src/initialize.ts (1)

70-81: Effective batching implementation for retry operations.

The batching approach prevents timeouts when retrying failed repositories. The smaller batch size of 100 (compared to 1000 in actions.ts) is appropriate for retry operations which may be more resource-intensive.

Consider adding error handling similar to the suggestion for actions.ts to ensure robustness during batch processing.

packages/backend/src/gitlab.ts (3)

10-10: Remove unused import.

The log import from "console" is not used anywhere in the code.

-import { log } from "console";

81-81: Consider making batch size configurable.

The hardcoded batch size of 10 may not be optimal for all GitLab instances. Consider making this configurable or using different batch sizes based on the instance capabilities.

-        const batchSize = 10;
+        const batchSize = config.batchSize || 10;

Also applies to: 130-130


85-120: Sequential batching may impact performance.

While sequential processing prevents API overloading, it could significantly slow down the operation. Consider processing a few batches concurrently (e.g., 2-3 batches) to balance performance and API limits.

-        // Process groups in batches of 10
-        for (let i = 0; i < config.groups.length; i += batchSize) {
-            const batch = config.groups.slice(i, i + batchSize);
-            logger.debug(`Processing batch ${i/batchSize + 1} of ${Math.ceil(config.groups.length/batchSize)} (${batch.length} groups)`);
-            
-            const batchResults = await Promise.allSettled(batch.map(async (group) => {
+        // Process groups in batches of 10 with limited concurrency
+        const maxConcurrentBatches = 2;
+        const batches = [];
+        for (let i = 0; i < config.groups.length; i += batchSize) {
+            batches.push(config.groups.slice(i, i + batchSize));
+        }
+        
+        for (let i = 0; i < batches.length; i += maxConcurrentBatches) {
+            const concurrentBatches = batches.slice(i, i + maxConcurrentBatches);
+            const batchPromises = concurrentBatches.map(async (batch, index) => {
+                logger.debug(`Processing batch ${i + index + 1} of ${batches.length} (${batch.length} groups)`);
+                return Promise.allSettled(batch.map(async (group) => {

Also applies to: 134-169

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8060ade and d90332d.

📒 Files selected for processing (4)
  • packages/backend/src/gitlab.ts (3 hunks)
  • packages/backend/src/repoManager.ts (1 hunks)
  • packages/web/src/actions.ts (2 hunks)
  • packages/web/src/initialize.ts (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
packages/backend/src/gitlab.ts (1)
packages/backend/src/utils.ts (2)
  • measure (9-17)
  • fetchWithRetry (92-119)
🔇 Additional comments (3)
packages/backend/src/repoManager.ts (1)

168-170: Excellent batching strategy for repository scheduling.

This implementation effectively addresses the core issue described in the PR objectives by preventing overwhelming the system when scheduling large numbers of repositories for indexing. The batch size of 100 aligns well with the database operation limits and job queue constraints.

The sequential processing approach is particularly important here as it prevents:

  • API timeouts from GitLab
  • Database connection exhaustion
  • Job queue overload
packages/backend/src/gitlab.ts (2)

49-78: Excellent implementation of the all-groups/all-users feature.

The logic properly handles the GitLab cloud restriction, uses retry mechanisms, and includes comprehensive error handling and logging. The approach of fetching all groups and users first, then processing them with the existing batched logic is well-designed.


89-118: Good error handling and logging implementation.

The error handling properly distinguishes between 404 (not found) and other errors, and the detailed logging will be helpful for debugging issues with large repository sets. The use of measure utility provides valuable performance insights.

Also applies to: 138-166

});
logger.debug(`Found ${_groups.length} groups in ${groupsDuration}ms.`);

config.groups = _groups.map(g => g.full_path);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Avoid mutating input parameters.

Modifying the config object directly creates unexpected side effects for callers. Consider storing the discovered groups and users in local variables instead.

-                config.groups = _groups.map(g => g.full_path);
+                const discoveredGroups = _groups.map(g => g.full_path);
+                config = { ...config, groups: discoveredGroups };
-                config.users = _users.map(u => u.username);
+                const discoveredUsers = _users.map(u => u.username);
+                config = { ...config, users: discoveredUsers };

Also applies to: 69-69

🤖 Prompt for AI Agents
In packages/backend/src/gitlab.ts at lines 57 and 69, avoid directly mutating
the input parameter `config` by assigning to its properties. Instead, create
local variables to hold the groups and users data derived from `_groups` and
other sources, and use these local variables within the function. This prevents
side effects on the caller's `config` object and maintains functional purity.

allRepos = allRepos.concat(validRepos);
notFound.orgs = notFoundOrgs;
logger.debug(`Found ${validRepos.length} valid repositories in groups.`);
logger.debug(`Not found groups: ${notFoundOrgs.join(', ')}`);
logger.debug(`These repositories will be downloaded: ${allRepos.map(repo => repo.path_with_namespace).join('\n')}`);
Copy link
Contributor

Choose a reason for hiding this comment

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

nit: synced not downloaded to be consistent with language elsewhere

@msukkari
Copy link
Contributor

msukkari commented Jul 3, 2025

Thanks for the change! I assume you've already tested this with larger configs? Would love to know if you've noticed a difference

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