sec-af icon indicating copy to clipboard operation
sec-af copied to clipboard

perf: incremental dedup — process findings as hunters complete

Open santoshkumarradha opened this issue 8 months ago • 0 comments

Problem

In `phases.py`, the hunt phase waits for ALL hunters to complete before running dedup:

```python hunt_results = await asyncio.gather(*hunt_calls, return_exceptions=True)

all_findings: list[RawFinding] = [] for idx, raw in enumerate(hunt_results): # ... collect all findings ...

ONLY NOW does dedup run

dedup_raw = await _runtime_router.call( f"{NODE_ID}.run_deduplicator", findings=[f.model_dump() for f in all_findings], recon_context=recon_context, repo_path=repo_path, ) ```

If one hunter is slow (e.g., business_logic on a large codebase takes 60s), findings from 11 fast hunters (completed in 20s) sit idle for 40s waiting for dedup to even start. Dedup itself then processes all findings as one batch.

Architectural Principle Violated

Principle 5 (Asynchronous Parallelism):

"Using asyncio.gather, the orchestrator can dispatch dozens or hundreds of AI calls simultaneously... is how we overcome the 'small, dumb LLM' constraint."

Proposed Design: Streaming Dedup via asyncio.Queue

Pattern: Producer-Consumer with Incremental Dedup

```python async def hunt_phase_streaming( repo_path: str, recon_context: dict[str, Any], strategies: list[HuntStrategy], max_concurrent_hunters: int = 4, ) -> HuntResult: findings_queue: asyncio.Queue[list[RawFinding] | None] = asyncio.Queue() all_findings: list[RawFinding] = [] deduped_so_far: list[RawFinding] = [] seen_fingerprints: set[str] = set()

semaphore = asyncio.Semaphore(max_concurrent_hunters)

async def _run_and_enqueue(strategy: HuntStrategy) -> None:
    async with semaphore:
        try:
            raw = await _runtime_router.call(
                f"{NODE_ID}.run_{strategy.value}_hunter", ...
            )
            payload = HuntResult.model_validate(...)
            await findings_queue.put(payload.findings)
        except Exception:
            await findings_queue.put([])  # Empty on failure

async def _incremental_dedup() -> list[RawFinding]:
    completed = 0
    while completed < len(strategies):
        batch = await findings_queue.get()
        if batch is None:
            break
        completed += 1
        
        # Programmatic dedup (fingerprint-based) — instant
        new_findings = []
        for f in batch:
            if f.fingerprint not in seen_fingerprints:
                seen_fingerprints.add(f.fingerprint)
                new_findings.append(f)
                all_findings.append(f)
        
        # AI-powered semantic dedup runs on new batch only
        if new_findings:
            # Dedup new findings against existing pool
            deduped_batch = await _semantic_dedup_incremental(
                new_findings, deduped_so_far
            )
            deduped_so_far.extend(deduped_batch)
    
    return deduped_so_far

# Launch hunters and dedup consumer in parallel
hunter_tasks = [_run_and_enqueue(s) for s in strategies]
dedup_task = asyncio.create_task(_incremental_dedup())

await asyncio.gather(*hunter_tasks)
await findings_queue.put(None)  # Sentinel
deduped = await dedup_task

return HuntResult(findings=deduped, ...)

```

Two-Tier Dedup

  1. Tier 1 (instant): Fingerprint-based — runs synchronously as findings arrive
  2. Tier 2 (AI-powered): Semantic similarity — runs on each new batch against existing findings

This means dedup for early findings is complete BEFORE late hunters finish. If combined with the streaming pipeline (#TBD), proved findings could start arriving while hunters are still running.

Acceptance Criteria

  • [ ] Dedup starts as soon as first hunter completes (not after all)
  • [ ] Fingerprint dedup is instant (no AI call needed)
  • [ ] Semantic dedup runs incrementally on new batches
  • [ ] Final dedup count matches or improves vs. current batch approach
  • [ ] Reasoner DAG preserved — dedup still visible as `run_deduplicator` in call graph
  • [ ] Measurable latency improvement when hunter completion times vary

Dependencies

  • Independent of other issues
  • Synergizes with: streaming pipeline (#TBD), dynamic adaptation (#TBD)

santoshkumarradha avatar Mar 05 '26 18:03 santoshkumarradha