Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

fix(security-scan): stop replace_findings from silently losing rows on duplicate keys (#1523)

Felix-Ayush19b1e7c4386e
diff --git a/packages/core/src/repowise/core/analysis/security_scan.py b/packages/core/src/repowise/core/analysis/security_scan.py
index 6d16f7696..7d986a00e 100644
--- a/packages/core/src/repowise/core/analysis/security_scan.py
+++ b/packages/core/src/repowise/core/analysis/security_scan.py
@@ -90,6 +90,17 @@ SECRET_KINDS: frozenset[str] = frozenset({"hardcoded_password", "hardcoded_secre
SYMBOL_NAME_KINDS: frozenset[str] = frozenset({"security_sensitive_symbol"})
+def _is_missing_table_error(exc: Exception) -> bool:
+ """True when *exc* is a 'no such table' / 'does not exist' failure.
+
+ ``replace_findings`` runs against a DB that may not yet have migrated the
+ ``security_findings`` table (pre-migration indexing). Those failures are
+ expected and skipped silently; everything else is a real error.
+ """
+ message = str(exc).lower()
+ return "no such table" in message or "does not exist" in message
+
+
class SecurityScanner:
"""Scan a single file for security signals and persist to the database."""
@@ -274,6 +285,14 @@ class SecurityScanner:
``scan --history`` are left intact. Uses raw SQL to stay independent of
any ORM session state; silently skips if the table doesn't exist yet
(pre-migration).
+
+ Re-running must never lose findings: two findings in one batch can
+ share a provenance key (e.g. two keyword symbols on the same line), and
+ a plain bulk INSERT would abort the whole batch at the first collision
+ — after the DELETE above already removed the file's prior rows. Rows
+ are therefore deduplicated in Python and inserted with the same
+ conflict-tolerant clauses as ``persist``, so a duplicate key is a no-op
+ rather than an abort.
"""
chunk_size = 400 # SQLite parameter-limit headroom, same as the CRUD layer
@@ -309,16 +328,51 @@ class SecurityScanner:
for file_path, findings in findings_by_file.items()
for finding in findings
]
- if rows:
+ # Two findings can collide on the unique provenance key
+ # (repository_id, file_path, kind, line_number, commit_sha) — e.g.
+ # two keyword symbols on the same line. Keeping only the first per
+ # key makes the batch insertable and lossless (the duplicates are
+ # redundant signals, not distinct rows).
+ seen: set[tuple[str, str, int]] = set()
+ deduped: list[dict] = []
+ for row in rows:
+ key = (row["file_path"], row["kind"], row["line"])
+ if key in seen:
+ continue
+ seen.add(key)
+ deduped.append(row)
+
+ if deduped:
+ uses_sqlite = self._uses_sqlite()
+ insert_prefix = (
+ "INSERT OR IGNORE INTO security_findings "
+ if uses_sqlite
+ else "INSERT INTO security_findings "
+ )
+ conflict_suffix = (
+ ""
+ if uses_sqlite
+ else " ON CONFLICT ON CONSTRAINT uq_security_finding_provenance DO NOTHING"
+ )
await self._session.execute(
text(
- "INSERT INTO security_findings "
- "(repository_id, file_path, kind, severity, snippet, line_number, "
+ insert_prefix
+ + "(repository_id, file_path, kind, severity, snippet, line_number, "
"commit_sha, commit_at, detected_at) "
"VALUES (:repo_id, :file_path, :kind, :severity, :snippet, :line, "
- ":commit_sha, :commit_at, :detected_at)"
+ ":commit_sha, :commit_at, :detected_at)" + conflict_suffix
),
- rows,
+ deduped,
)
- except Exception: # table may not exist pre-migration
- return
+ except Exception as exc:
+ # Pre-migration, the table does not exist yet — silently skip (the
+ # historical contract for indexing against a not-yet-migrated DB).
+ # Any other failure is a real one and must not be swallowed: a
+ # silently dropped batch is how findings disappear.
+ if _is_missing_table_error(exc):
+ return
+ logger.exception(
+ "security_findings_replace_failed paths=%d rows=%d",
+ len(scanned_paths),
+ len(rows) if "rows" in locals() else 0,
+ )
diff --git a/tests/unit/analysis/test_security_scan.py b/tests/unit/analysis/test_security_scan.py
index 84e758329..6bf0c12f1 100644
--- a/tests/unit/analysis/test_security_scan.py
+++ b/tests/unit/analysis/test_security_scan.py
@@ -222,3 +222,64 @@ class TestPersistSecurityFindings:
rows = asyncio.run(_run())
assert ("auth.py", "security_sensitive_symbol", 7) in rows
+
+ def test_replace_findings_duplicate_key_does_not_lose_rows(self, tmp_path: Path) -> None:
+ """Two findings sharing a provenance key must not abort the batch and
+ drop the file's other rows (regression for the bulk-INSERT abort that
+ swallowed IntegrityError and silently truncated the insert)."""
+ from repowise.core.analysis.security_scan import SecurityScanner
+ from repowise.core.persistence import get_session
+
+ async def _run():
+ engine, sf = await _fresh_session_factory(tmp_path)
+ async with get_session(sf) as session:
+ scanner = SecurityScanner(session, "repo-1")
+ await scanner.replace_findings(
+ {
+ "a.py": [
+ {"kind": "hardcoded_password", "severity": "high", "line": 1},
+ {"kind": "security_sensitive_symbol", "severity": "low", "line": 7},
+ {"kind": "security_sensitive_symbol", "severity": "low", "line": 7},
+ ],
+ },
+ ["a.py"],
+ )
+ rows = await _rows(sf)
+ await engine.dispose()
+ return rows
+
+ rows = asyncio.run(_run())
+ assert sorted(rows) == [
+ ("a.py", "hardcoded_password", 1),
+ ("a.py", "security_sensitive_symbol", 7),
+ ]
+
+ def test_replace_findings_rescan_keeps_prior_and_new_rows(self, tmp_path: Path) -> None:
+ """Re-running replace_findings over the same file must yield the same
+ full row set — duplicates on the provenance key are no-ops, never a
+ partial insert."""
+ from repowise.core.analysis.security_scan import SecurityScanner
+ from repowise.core.persistence import get_session
+
+ async def _run():
+ engine, sf = await _fresh_session_factory(tmp_path)
+ findings = {
+ "a.py": [
+ {"kind": "hardcoded_password", "severity": "high", "line": 1},
+ {"kind": "security_sensitive_symbol", "severity": "low", "line": 7},
+ {"kind": "security_sensitive_symbol", "severity": "low", "line": 7},
+ ],
+ }
+ for _ in range(2):
+ async with get_session(sf) as session:
+ scanner = SecurityScanner(session, "repo-1")
+ await scanner.replace_findings(findings, ["a.py"])
+ rows = await _rows(sf)
+ await engine.dispose()
+ return rows
+
+ rows = asyncio.run(_run())
+ assert sorted(rows) == [
+ ("a.py", "hardcoded_password", 1),
+ ("a.py", "security_sensitive_symbol", 7),
+ ]