Skip to content

Add projection to mongo sampling - #344

Merged
adiom-mark merged 1 commit into
mainfrom
sample-factor-project
Oct 30, 2025
Merged

Add projection to mongo sampling#344
adiom-mark merged 1 commit into
mainfrom
sample-factor-project

Conversation

@adiom-mark

@adiom-mark adiom-mark commented Oct 30, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • Bug Fixes
    • Sampling now returns explicit errors for invalid configurations instead of silently adjusting parameters
    • Aggregation immediately fails on error to avoid partial results
    • Improved error messages with contextual information for easier troubleshooting
    • Added warning notifications for unusually large sample sizes
    • Reduced data processed during sampling by projecting only identifiers before sampling and sorting

@coderabbitai

coderabbitai Bot commented Oct 30, 2025

Copy link
Copy Markdown

Walkthrough

Sampling logic in the MongoDB connector now enforces a stricter sample-size threshold, projects only _id before sampling and sorting, logs very large sample requests, and wraps aggregation errors with contextual messages, returning immediately on aggregation failures.

Changes

Cohort / File(s) Summary
MongoDB sampling & aggregation
connectors/mongo/conn.go
Replaced downward-adjustment path with an explicit error when numSamples*21 >= count. Added warning log when numSamples > 1,000,000. Updated aggregation pipeline to project _id before $sample and $sort. Wrap aggregation errors with fmt.Errorf("%w", err) and return immediately on aggregation failures; changed sample-result error handling to return a formatted error instead of silently adjusting counts.

Sequence Diagram

sequenceDiagram
    participant Caller
    participant SamplingLogic
    participant MongoDB
    participant ErrorHandler

    Caller->>SamplingLogic: Request sampling
    SamplingLogic->>SamplingLogic: Compute numSamples

    alt numSamples > 1_000_000
        SamplingLogic->>SamplingLogic: Log warning (large sample)
    end

    alt numSamples*21 >= count
        SamplingLogic->>ErrorHandler: Build formatted error (adjust factor/target)
        ErrorHandler-->>Caller: Return error
    else Threshold OK
        SamplingLogic->>MongoDB: Run aggregation (project _id → $sample → $sort)
        alt aggregation succeeds
            MongoDB-->>SamplingLogic: Return sampled ids
            SamplingLogic-->>Caller: Return samples
        else aggregation fails
            MongoDB-->>SamplingLogic: Error
            SamplingLogic->>ErrorHandler: Wrap error with context (%w)
            ErrorHandler-->>Caller: Return error immediately
        end
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Pay attention to:
    • Correctness and intent of the new numSamples*21 >= count threshold.
    • Semantic impact of projecting only _id before sampling and sorting.
    • Proper preservation of error context when wrapping and returning aggregation errors.

Possibly related PRs

Poem

🐇 I nibble at code, I hop through each line,

Project the IDs first, then sample just fine.
No quiet downscales — loud errors declare,
A million-plus warns me, so handle with care.
Wrapped errors tidy, the flow now is clear.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "Add projection to mongo sampling" directly corresponds to one of the documented changes in the pull request: the insertion of a projection stage to the aggregation pipeline that emits only the _id field before sampling and sorting. This is a real and verifiable aspect of the changeset. However, the pull request also includes other significant changes such as replacing autonomous downward adjustment with error-based control flow, improved error handling and formatting, and adding warning logs for large sample counts. The title captures the projection addition but does not fully encompass these broader behavioral changes to the sampling logic, making it partially related to the changeset rather than fully summarizing the main point.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch sample-factor-project

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9080151 and f0765f8.

📒 Files selected for processing (1)
  • connectors/mongo/conn.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build
🔇 Additional comments (3)
connectors/mongo/conn.go (3)

238-240: Good addition: warning for expensive sampling operations.

The warning log for large sample requests (>1M) is helpful for identifying potentially expensive queries. The structured logging with the actual sample count is well done.


241-241: Good optimization: project before sorting.

Adding the $project stage to emit only the _id field before sorting reduces the amount of data MongoDB needs to sort, which should improve performance for large sample sizes. This is a solid optimization since only the _id values are needed for partition boundaries.


243-243: Good practice: proper error wrapping.

The error wrapping using fmt.Errorf with %w is correct and follows Go best practices. Including the number of samples in the error message provides helpful context for debugging.


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 and usage tips.

@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

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 74daf1b and 9080151.

📒 Files selected for processing (1)
  • connectors/mongo/conn.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build
🔇 Additional comments (3)
connectors/mongo/conn.go (3)

238-240: Good observability improvement.

The warning log for large sample sizes helps operators identify potentially expensive operations before they impact performance.


241-241: Excellent performance optimization.

Adding the $project stage to emit only the _id field before sampling significantly reduces data transfer overhead, as the downstream code (lines 247-260) only requires the _id field.


243-243: LGTM!

The improved error wrapping with %w maintains the error chain while adding valuable context about the number of samples requested.

Comment thread connectors/mongo/conn.go
Comment on lines +235 to 237
if numSamples*21 >= count {
return fmt.Errorf("too many samples requested (%v of %v)- adjust sample factor or target documents per partition", numSamples, count)
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Behavioral change: error instead of auto-adjustment.

The sampling logic now returns an error when numSamples*21 >= count instead of adjusting numSamples downward. This is a breaking change that could affect existing configurations that previously relied on auto-adjustment.

Additionally, there's a minor formatting issue in the error message.

Apply this diff to fix the formatting:

-			return fmt.Errorf("too many samples requested (%v of %v)- adjust sample factor or target documents per partition", numSamples, count)
+			return fmt.Errorf("too many samples requested (%v of %v) - adjust sample factor or target documents per partition", numSamples, count)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if numSamples*21 >= count {
return fmt.Errorf("too many samples requested (%v of %v)- adjust sample factor or target documents per partition", numSamples, count)
}
if numSamples*21 >= count {
return fmt.Errorf("too many samples requested (%v of %v) - adjust sample factor or target documents per partition", numSamples, count)
}

Comment thread connectors/mongo/conn.go
}
res, err := col.Aggregate(ctx, mongo.Pipeline{{{"$sample", bson.D{{"size", numSamples}}}}, {{"$sort", bson.D{{"_id", 1}}}}})
if numSamples > 1000000 {
slog.Warn("More than 1000000 samples requested", "samples", numSamples)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Maybe elaborate on why it's bad (can cause the sampling query to run long or fail) and what to do (adjust the sampling factor or increase task size

@adiom-mark
adiom-mark force-pushed the sample-factor-project branch from 9080151 to f0765f8 Compare October 30, 2025 21:59
@adiom-mark
adiom-mark merged commit db71687 into main Oct 30, 2025
2 checks passed
@adiom-mark
adiom-mark deleted the sample-factor-project branch October 30, 2025 22:16
adiom-mark added a commit that referenced this pull request Oct 30, 2025
Co-authored-by: Mark C <mark@Marks-MacBook-Pro.local>
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