Skip to content

Conversation

jjhwan-h
Copy link

@jjhwan-h jjhwan-h commented Jul 31, 2025

Summary

This PR addresses issue #2152, which causes response files to be overwritten even when the -sd (SkipDedupe) flag is used.

What was the issue?

When the -sd flag is enabled, input targets are processed without deduplication. However, the responses are still written to the same file path based on the SHA1 hash of the URL, leading to overwritten output files.

What’s changed?

  • When SkipDedupe is enabled and a response file with the same name already exists, the response will be written to a new file with a suffix (_1, _2, ...).
  • Repeated input targets are now counted using HybridMap, and the number of processing iterations is determined based on this count.
  • Modified countTargetFromRawTarget to return a known duplicateTargetErr when deduplication is disabled.
  • Refactored response writing logic in analyze and process to ensure unique file writes under concurrency.

Why is this useful?

This change ensures:

  • Accurate tracking and storage of multiple response outputs for identical input targets.
  • Prevents unintentional data loss due to file overwrites.
  • Honors the intent behind the -sd flag.

Result

# test.txt
localhost:8000
localhost:9000
localhost:8000
localhost:9000
localhost:8000
localhost:9000
localhost:8000
localhost:9000
$./httpx/httpx -l test.txt -stream -skip-dedupe -sr
$tree output/response/                                                                                                                            
output/response/                                                                                                                                                                         
├── index.txt
├── localhost_8000
│   ├── 59bd7616010ed02cd66f44e94e9368776966fe3b.txt
│   ├── 59bd7616010ed02cd66f44e94e9368776966fe3b_1.txt
│   ├── 59bd7616010ed02cd66f44e94e9368776966fe3b_2.txt
│   └── 59bd7616010ed02cd66f44e94e9368776966fe3b_3.txt
└── localhost_9000
    ├── 981d6875d791d0a1a28393b5ec62d61dff1e977f.txt
    ├── 981d6875d791d0a1a28393b5ec62d61dff1e977f_1.txt
    ├── 981d6875d791d0a1a28393b5ec62d61dff1e977f_2.txt
    └── 981d6875d791d0a1a28393b5ec62d61dff1e977f_3.txt

2 directories, 9 files
$ ./httpx/httpx -l test.txt -skip-dedupe -sr
 $ tree output/response/
output/response/
├── index.txt
├── localhost_8000
│   ├── 59bd7616010ed02cd66f44e94e9368776966fe3b.txt
│   ├── 59bd7616010ed02cd66f44e94e9368776966fe3b_1.txt
│   ├── 59bd7616010ed02cd66f44e94e9368776966fe3b_2.txt
│   └── 59bd7616010ed02cd66f44e94e9368776966fe3b_3.txt
└── localhost_9000
    ├── 981d6875d791d0a1a28393b5ec62d61dff1e977f.txt
    ├── 981d6875d791d0a1a28393b5ec62d61dff1e977f_1.txt
    ├── 981d6875d791d0a1a28393b5ec62d61dff1e977f_2.txt
    └── 981d6875d791d0a1a28393b5ec62d61dff1e977f_3.txt

2 directories, 9 files
$./httpx/httpx -l test.txt -sr
output/
└── response
    ├── index.txt
    ├── localhost_8000
    │   └── 59bd7616010ed02cd66f44e94e9368776966fe3b.txt
    └── localhost_9000
        └── 981d6875d791d0a1a28393b5ec62d61dff1e977f.txt

3 directories, 3 files
$ ./httpx/httpx -l test.txt -stream -sr
$ tree output/
output/
└── response
    ├── index.txt
    ├── localhost_8000
    │   └── 59bd7616010ed02cd66f44e94e9368776966fe3b.txt
    └── localhost_9000
        └── 981d6875d791d0a1a28393b5ec62d61dff1e977f.txt

3 directories, 3 files

Related issue

Closes #2152

Summary by CodeRabbit

  • New Features

    • Duplicate targets are now explicitly detected and can be processed multiple times if configured.
    • When saving response files, unique filenames are automatically generated to prevent overwriting existing files.
  • Bug Fixes

    • Improved handling of duplicate targets to ensure accurate counting and processing.
  • Tests

    • Updated tests to verify correct detection and handling of duplicate targets.

Copy link

coderabbitai bot commented Jul 31, 2025

Walkthrough

The code introduces explicit handling for duplicate targets by tracking their counts and processing each occurrence accordingly, especially when deduplication is disabled. It also updates file writing logic to avoid overwriting response files by generating unique filenames. Test cases are updated to reflect the new duplicate target error handling.

Changes

Cohort / File(s) Change Summary
Duplicate Target Handling & Counting
runner/runner.go
Introduced duplicateTargetErr for duplicate detection; refactored target counting logic to track and process duplicate targets based on user options. The internal map now stores counts as byte slices, and processing repeats per count when deduplication is skipped.
Safe Response File Writing
runner/runner.go
Removed response file saving from output goroutine; updated file writing to use exclusive creation and unique filename suffixes to prevent overwrites when deduplication is disabled.
Test Updates for Duplicate Detection
runner/runner_test.go
Modified tests to set SkipDedupe to false and assert that duplicateTargetErr is returned for duplicate targets, ensuring correct error handling.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Runner
    participant FileSystem

    User->>Runner: Provide target list with duplicates, set -skip-dedupe
    Runner->>Runner: Parse targets, count duplicates
    loop For each duplicate count
        Runner->>Runner: Process target
        Runner->>FileSystem: Write response file (with unique name if needed)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
Disable dedupe in response file write when -sd is used (#2152)
Ensure unique response files for duplicate targets (#2152)

Poem

A rabbit hops with code so neat,
Now every duplicate gets its treat!
No more files lost in the fray,
Each response finds its own way.
With careful count and cheerful cheer,
Duplicates are welcome here!
🐇✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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 generate unit tests to generate unit tests for 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 (1)
runner/runner.go (1)

2152-2176: Consider adding a safety limit to prevent potential infinite loops.

While the file creation logic correctly handles duplicates, there's no upper limit on the suffix counter. In edge cases or under concurrent load, this could theoretically loop indefinitely.

Consider adding a reasonable upper limit:

 finalPath := responsePath
 idx := 0
+const maxSuffixAttempts = 1000
 for {
+    if idx >= maxSuffixAttempts {
+        gologger.Error().Msgf("Exceeded maximum attempts to create unique file for '%s'", responsePath)
+        break
+    }
     targetPath := finalPath
     if idx > 0 {
         basePath := strings.TrimSuffix(responsePath, ".txt")
         targetPath = fmt.Sprintf("%s_%d.txt", basePath, idx)
     }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between faac44c and 3cac134.

📒 Files selected for processing (2)
  • runner/runner.go (6 hunks)
  • runner/runner_test.go (3 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
runner/runner_test.go (1)
runner/options.go (1)
  • Options (173-351)
🔇 Additional comments (5)
runner/runner.go (4)

448-449: LGTM! Good use of a sentinel error for explicit duplicate detection.

The error declaration follows Go's best practices for sentinel errors.


642-645: Good improvement to error handling!

Making duplicate detection explicit with an error return is better than silently returning 0. This allows callers to handle duplicates appropriately based on their needs.


1245-1267: Well-structured refactoring for repeated target processing!

The runProcess helper function cleanly encapsulates the logic for processing targets multiple times based on their count. Good handling of edge cases with the default to 1 when parsing fails.


455-465: Consider initializing counts consistently.

The current implementation always sets the initial count to "1" for new targets (line 458), but this might not accurately reflect the actual number of times a target appears in the input. Additionally, the error from strconv.Atoi at line 461 is ignored, which could lead to unexpected behavior if the stored value is corrupted.

Consider this more robust implementation:

-				r.hm.Set(target, []byte("1")) //nolint
+				r.hm.Set(target, []byte("1"))
 			} else if r.options.SkipDedupe && errors.Is(err, duplicateTargetErr) {
 				if v, ok := r.hm.Get(target); ok {
-					cnt, _ := strconv.Atoi(string(v))
+					cnt, err := strconv.Atoi(string(v))
+					if err != nil {
+						// Handle corrupted count, default to 1
+						cnt = 1
+					}
 					r.hm.Set(target, []byte(strconv.Itoa(cnt+1)))
 					numHosts += 1
 				}

Likely an incorrect or invalid review comment.

runner/runner_test.go (1)

10-10: Test updates correctly reflect the new duplicate handling behavior!

Good changes:

  • Explicitly setting SkipDedupe: false makes the test's intent clear
  • Using errors.Is is the correct way to check for sentinel errors in Go
  • The test properly validates that duplicates are detected and return the expected error

Also applies to: 128-130, 145-145

Comment on lines +622 to 632
expandedTarget, err := r.countTargetFromRawTarget(target)
if err == nil && expandedTarget > 0 {
numTargets += expandedTarget
r.hm.Set(target, nil) //nolint
r.hm.Set(target, []byte("1")) //nolint
} else if r.options.SkipDedupe && errors.Is(err, duplicateTargetErr) {
if v, ok := r.hm.Get(target); ok {
cnt, _ := strconv.Atoi(string(v))
r.hm.Set(target, []byte(strconv.Itoa(cnt+1)))
numTargets += 1
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Extract duplicate counting logic to reduce code duplication.

This logic is duplicated from prepareInput. Consider extracting it into a helper method to maintain DRY principles and ensure consistent behavior.

Consider creating a helper method:

func (r *Runner) incrementTargetCount(target string) {
    if v, ok := r.hm.Get(target); ok {
        cnt, err := strconv.Atoi(string(v))
        if err != nil {
            cnt = 1
        }
        r.hm.Set(target, []byte(strconv.Itoa(cnt+1)))
    }
}

Then use it in both locations:

 } else if r.options.SkipDedupe && errors.Is(err, duplicateTargetErr) {
-    if v, ok := r.hm.Get(target); ok {
-        cnt, _ := strconv.Atoi(string(v))
-        r.hm.Set(target, []byte(strconv.Itoa(cnt+1)))
-        numTargets += 1
-    }
+    r.incrementTargetCount(target)
+    numTargets += 1
 }
🤖 Prompt for AI Agents
In runner/runner.go around lines 622 to 632, the logic for incrementing the
count of duplicate targets is duplicated from the prepareInput method. Extract
this duplicate counting logic into a new helper method on the Runner struct, for
example incrementTargetCount, which safely retrieves the current count, handles
conversion errors by defaulting to 1, increments the count, and updates the map.
Replace the duplicated code in both places with calls to this new helper method
to adhere to DRY principles and maintain consistent behavior.

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.

disable dedupe in response file write when -sd is used
1 participant