mulle-roam-code 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- mulle_roam_code-0.0.1.dist-info/METADATA +1590 -0
- mulle_roam_code-0.0.1.dist-info/RECORD +257 -0
- mulle_roam_code-0.0.1.dist-info/WHEEL +5 -0
- mulle_roam_code-0.0.1.dist-info/entry_points.txt +3 -0
- mulle_roam_code-0.0.1.dist-info/licenses/LICENSE +21 -0
- mulle_roam_code-0.0.1.dist-info/top_level.txt +1 -0
- roam/__init__.py +8 -0
- roam/__main__.py +5 -0
- roam/analysis/__init__.py +1 -0
- roam/analysis/effects.py +639 -0
- roam/analysis/taint.py +689 -0
- roam/api.py +238 -0
- roam/bridges/__init__.py +3 -0
- roam/bridges/base.py +49 -0
- roam/bridges/bridge_config.py +218 -0
- roam/bridges/bridge_protobuf.py +352 -0
- roam/bridges/bridge_rest_api.py +242 -0
- roam/bridges/bridge_salesforce.py +198 -0
- roam/bridges/bridge_template.py +247 -0
- roam/bridges/registry.py +51 -0
- roam/catalog/__init__.py +0 -0
- roam/catalog/detectors.py +2242 -0
- roam/catalog/fixes.py +86 -0
- roam/catalog/smells.py +599 -0
- roam/catalog/tasks.py +1260 -0
- roam/cli.py +548 -0
- roam/commands/__init__.py +0 -0
- roam/commands/changed_files.py +139 -0
- roam/commands/cmd_adversarial.py +699 -0
- roam/commands/cmd_affected.py +432 -0
- roam/commands/cmd_affected_tests.py +375 -0
- roam/commands/cmd_agent_context.py +168 -0
- roam/commands/cmd_agent_export.py +890 -0
- roam/commands/cmd_agent_plan.py +315 -0
- roam/commands/cmd_ai_ratio.py +765 -0
- roam/commands/cmd_ai_readiness.py +775 -0
- roam/commands/cmd_alerts.py +409 -0
- roam/commands/cmd_annotate.py +210 -0
- roam/commands/cmd_api_changes.py +796 -0
- roam/commands/cmd_api_drift.py +781 -0
- roam/commands/cmd_attest.py +913 -0
- roam/commands/cmd_auth_gaps.py +799 -0
- roam/commands/cmd_bisect.py +216 -0
- roam/commands/cmd_breaking.py +464 -0
- roam/commands/cmd_budget.py +413 -0
- roam/commands/cmd_bus_factor.py +403 -0
- roam/commands/cmd_capsule.py +275 -0
- roam/commands/cmd_check_rules.py +574 -0
- roam/commands/cmd_clean.py +147 -0
- roam/commands/cmd_closure.py +294 -0
- roam/commands/cmd_clusters.py +457 -0
- roam/commands/cmd_codeowners.py +600 -0
- roam/commands/cmd_complexity.py +364 -0
- roam/commands/cmd_config.py +310 -0
- roam/commands/cmd_context.py +1151 -0
- roam/commands/cmd_conventions.py +697 -0
- roam/commands/cmd_coupling.py +462 -0
- roam/commands/cmd_coverage_gaps.py +638 -0
- roam/commands/cmd_cut.py +235 -0
- roam/commands/cmd_dark_matter.py +127 -0
- roam/commands/cmd_dashboard.py +365 -0
- roam/commands/cmd_dead.py +1585 -0
- roam/commands/cmd_debt.py +731 -0
- roam/commands/cmd_deps.py +121 -0
- roam/commands/cmd_describe.py +959 -0
- roam/commands/cmd_dev_profile.py +580 -0
- roam/commands/cmd_diagnose.py +377 -0
- roam/commands/cmd_diff.py +633 -0
- roam/commands/cmd_digest.py +214 -0
- roam/commands/cmd_doc_staleness.py +334 -0
- roam/commands/cmd_docs_coverage.py +193 -0
- roam/commands/cmd_doctor.py +319 -0
- roam/commands/cmd_drift.py +377 -0
- roam/commands/cmd_duplicates.py +559 -0
- roam/commands/cmd_effects.py +362 -0
- roam/commands/cmd_endpoints.py +768 -0
- roam/commands/cmd_entry_points.py +358 -0
- roam/commands/cmd_fan.py +311 -0
- roam/commands/cmd_file.py +334 -0
- roam/commands/cmd_fingerprint.py +172 -0
- roam/commands/cmd_fitness.py +723 -0
- roam/commands/cmd_fn_coupling.py +295 -0
- roam/commands/cmd_forecast.py +366 -0
- roam/commands/cmd_grep.py +282 -0
- roam/commands/cmd_guard.py +434 -0
- roam/commands/cmd_health.py +922 -0
- roam/commands/cmd_hooks.py +458 -0
- roam/commands/cmd_hotspots.py +606 -0
- roam/commands/cmd_impact.py +228 -0
- roam/commands/cmd_index.py +102 -0
- roam/commands/cmd_ingest_trace.py +143 -0
- roam/commands/cmd_init.py +166 -0
- roam/commands/cmd_intent.py +459 -0
- roam/commands/cmd_invariants.py +301 -0
- roam/commands/cmd_layers.py +387 -0
- roam/commands/cmd_map.py +275 -0
- roam/commands/cmd_math.py +213 -0
- roam/commands/cmd_mcp_setup.py +135 -0
- roam/commands/cmd_metrics.py +663 -0
- roam/commands/cmd_migration_safety.py +712 -0
- roam/commands/cmd_minimap.py +519 -0
- roam/commands/cmd_missing_index.py +885 -0
- roam/commands/cmd_module.py +204 -0
- roam/commands/cmd_mutate.py +400 -0
- roam/commands/cmd_n1.py +967 -0
- roam/commands/cmd_onboard.py +740 -0
- roam/commands/cmd_orchestrate.py +180 -0
- roam/commands/cmd_orphan_routes.py +754 -0
- roam/commands/cmd_over_fetch.py +633 -0
- roam/commands/cmd_owner.py +299 -0
- roam/commands/cmd_partition.py +714 -0
- roam/commands/cmd_path_coverage.py +564 -0
- roam/commands/cmd_patterns.py +689 -0
- roam/commands/cmd_plan.py +616 -0
- roam/commands/cmd_plan_refactor.py +432 -0
- roam/commands/cmd_pr_diff.py +292 -0
- roam/commands/cmd_pr_risk.py +677 -0
- roam/commands/cmd_preflight.py +706 -0
- roam/commands/cmd_relate.py +405 -0
- roam/commands/cmd_report.py +304 -0
- roam/commands/cmd_reset.py +117 -0
- roam/commands/cmd_risk.py +533 -0
- roam/commands/cmd_rules.py +319 -0
- roam/commands/cmd_safe_delete.py +224 -0
- roam/commands/cmd_safe_zones.py +295 -0
- roam/commands/cmd_schema.py +166 -0
- roam/commands/cmd_search.py +295 -0
- roam/commands/cmd_search_semantic.py +101 -0
- roam/commands/cmd_secrets.py +636 -0
- roam/commands/cmd_semantic_diff.py +538 -0
- roam/commands/cmd_simulate.py +296 -0
- roam/commands/cmd_simulate_departure.py +632 -0
- roam/commands/cmd_sketch.py +160 -0
- roam/commands/cmd_smells.py +179 -0
- roam/commands/cmd_snapshot.py +50 -0
- roam/commands/cmd_spectral.py +183 -0
- roam/commands/cmd_split.py +432 -0
- roam/commands/cmd_suggest_refactoring.py +486 -0
- roam/commands/cmd_suggest_reviewers.py +491 -0
- roam/commands/cmd_supply_chain.py +831 -0
- roam/commands/cmd_symbol.py +135 -0
- roam/commands/cmd_syntax_check.py +301 -0
- roam/commands/cmd_test_gaps.py +574 -0
- roam/commands/cmd_testmap.py +308 -0
- roam/commands/cmd_tour.py +377 -0
- roam/commands/cmd_trace.py +304 -0
- roam/commands/cmd_trend.py +461 -0
- roam/commands/cmd_trends.py +929 -0
- roam/commands/cmd_understand.py +763 -0
- roam/commands/cmd_uses.py +170 -0
- roam/commands/cmd_verify.py +812 -0
- roam/commands/cmd_verify_imports.py +435 -0
- roam/commands/cmd_vibe_check.py +932 -0
- roam/commands/cmd_visualize.py +361 -0
- roam/commands/cmd_vuln_map.py +139 -0
- roam/commands/cmd_vuln_reach.py +289 -0
- roam/commands/cmd_vulns.py +414 -0
- roam/commands/cmd_watch.py +759 -0
- roam/commands/cmd_weather.py +118 -0
- roam/commands/cmd_why.py +325 -0
- roam/commands/cmd_ws.py +755 -0
- roam/commands/cmd_xlang.py +170 -0
- roam/commands/context_helpers.py +1137 -0
- roam/commands/gate_presets.py +222 -0
- roam/commands/graph_helpers.py +93 -0
- roam/commands/metrics_history.py +298 -0
- roam/commands/next_steps.py +107 -0
- roam/commands/resolve.py +302 -0
- roam/competitor_site_data.py +2229 -0
- roam/coverage_reports.py +462 -0
- roam/db/__init__.py +0 -0
- roam/db/connection.py +359 -0
- roam/db/queries.py +151 -0
- roam/db/schema.py +335 -0
- roam/exit_codes.py +100 -0
- roam/graph/__init__.py +43 -0
- roam/graph/anomaly.py +493 -0
- roam/graph/builder.py +61 -0
- roam/graph/clusters.py +286 -0
- roam/graph/cycles.py +210 -0
- roam/graph/dark_matter.py +207 -0
- roam/graph/diff.py +467 -0
- roam/graph/fingerprint.py +297 -0
- roam/graph/layers.py +134 -0
- roam/graph/pagerank.py +171 -0
- roam/graph/partition.py +437 -0
- roam/graph/pathfinding.py +119 -0
- roam/graph/propagation.py +208 -0
- roam/graph/simulate.py +286 -0
- roam/graph/spectral.py +260 -0
- roam/index/__init__.py +5 -0
- roam/index/complexity.py +1108 -0
- roam/index/discovery.py +338 -0
- roam/index/file_roles.py +586 -0
- roam/index/git_stats.py +577 -0
- roam/index/incremental.py +75 -0
- roam/index/indexer.py +1191 -0
- roam/index/parser.py +461 -0
- roam/index/relations.py +537 -0
- roam/index/symbols.py +71 -0
- roam/index/test_conventions.py +508 -0
- roam/languages/__init__.py +21 -0
- roam/languages/apex_lang.py +241 -0
- roam/languages/aura_lang.py +228 -0
- roam/languages/base.py +111 -0
- roam/languages/c_lang.py +458 -0
- roam/languages/csharp_lang.py +1215 -0
- roam/languages/foxpro_lang.py +1554 -0
- roam/languages/generic_lang.py +702 -0
- roam/languages/go_lang.py +392 -0
- roam/languages/hcl_lang.py +398 -0
- roam/languages/java_lang.py +418 -0
- roam/languages/javascript_lang.py +799 -0
- roam/languages/kotlin_lang.py +147 -0
- roam/languages/objc_lang.py +401 -0
- roam/languages/php_lang.py +696 -0
- roam/languages/python_lang.py +850 -0
- roam/languages/registry.py +283 -0
- roam/languages/ruby_lang.py +429 -0
- roam/languages/rust_lang.py +545 -0
- roam/languages/sfxml_lang.py +276 -0
- roam/languages/swift_lang.py +173 -0
- roam/languages/typescript_lang.py +323 -0
- roam/languages/visualforce_lang.py +151 -0
- roam/languages/yaml_lang.py +566 -0
- roam/mcp_server.py +4794 -0
- roam/output/__init__.py +0 -0
- roam/output/formatter.py +557 -0
- roam/output/mermaid.py +62 -0
- roam/output/sarif.py +897 -0
- roam/output/schema_registry.py +57 -0
- roam/plugins.py +208 -0
- roam/refactor/__init__.py +0 -0
- roam/refactor/codegen.py +106 -0
- roam/refactor/transforms.py +711 -0
- roam/rules/__init__.py +0 -0
- roam/rules/ast_match.py +238 -0
- roam/rules/builtin.py +617 -0
- roam/rules/dataflow.py +515 -0
- roam/rules/engine.py +943 -0
- roam/runtime/__init__.py +3 -0
- roam/runtime/hotspots.py +138 -0
- roam/runtime/trace_ingest.py +535 -0
- roam/search/__init__.py +1 -0
- roam/search/framework_packs.py +673 -0
- roam/search/index_embeddings.py +732 -0
- roam/search/onnx_embeddings.py +233 -0
- roam/search/tfidf.py +355 -0
- roam/security/__init__.py +1 -0
- roam/security/vuln_reach.py +246 -0
- roam/security/vuln_store.py +334 -0
- roam/surface_counts.py +158 -0
- roam/workspace/__init__.py +3 -0
- roam/workspace/aggregator.py +426 -0
- roam/workspace/api_scanner.py +538 -0
- roam/workspace/config.py +95 -0
- roam/workspace/db.py +136 -0
|
@@ -0,0 +1,2242 @@
|
|
|
1
|
+
"""Algorithm detection: query DB signals to find suboptimal patterns.
|
|
2
|
+
|
|
3
|
+
Each detector has signature ``(conn) -> list[dict]`` and returns findings
|
|
4
|
+
with fields: task_id, detected_way, suggested_way, symbol_id, symbol_name,
|
|
5
|
+
kind, location, confidence, reason.
|
|
6
|
+
|
|
7
|
+
Design principles (informed by research):
|
|
8
|
+
- Structural AST patterns (loop depth, accumulator, subscript) are more
|
|
9
|
+
reliable than function-name matching alone.
|
|
10
|
+
- Name matching is a confidence booster, not a gate.
|
|
11
|
+
- Idiom-only improvements (same Big-O) get ``low`` confidence.
|
|
12
|
+
- Genuine complexity-class improvements get ``medium`` or ``high``.
|
|
13
|
+
- Suppress known false-positive patterns (grid traversal, intentional polling).
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import json
|
|
19
|
+
import os
|
|
20
|
+
import re
|
|
21
|
+
|
|
22
|
+
from roam.catalog.tasks import best_way
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _is_test_path(path: str) -> bool:
|
|
26
|
+
p = path.replace("\\", "/").lower()
|
|
27
|
+
base = os.path.basename(p)
|
|
28
|
+
if base.startswith("test_") or base.endswith("_test.py"):
|
|
29
|
+
return True
|
|
30
|
+
if "tests/" in p or "test/" in p or "__tests__/" in p or "spec/" in p:
|
|
31
|
+
return True
|
|
32
|
+
return False
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _loc(path: str, line) -> str:
|
|
36
|
+
if line is not None:
|
|
37
|
+
return f"{path}:{line}"
|
|
38
|
+
return path
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _finding(
|
|
42
|
+
task_id,
|
|
43
|
+
detected_way,
|
|
44
|
+
sym,
|
|
45
|
+
reason,
|
|
46
|
+
confidence="medium",
|
|
47
|
+
*,
|
|
48
|
+
evidence=None,
|
|
49
|
+
fix=None,
|
|
50
|
+
):
|
|
51
|
+
bw = best_way(task_id)
|
|
52
|
+
finding = {
|
|
53
|
+
"task_id": task_id,
|
|
54
|
+
"detected_way": detected_way,
|
|
55
|
+
"suggested_way": bw["id"] if bw else "",
|
|
56
|
+
"symbol_id": sym["id"],
|
|
57
|
+
"symbol_name": sym["qualified_name"] or sym["name"],
|
|
58
|
+
"kind": sym["kind"],
|
|
59
|
+
"location": _loc(sym["file_path"], sym["line_start"]),
|
|
60
|
+
"confidence": confidence,
|
|
61
|
+
"reason": reason,
|
|
62
|
+
}
|
|
63
|
+
if evidence:
|
|
64
|
+
finding["evidence"] = evidence
|
|
65
|
+
if fix:
|
|
66
|
+
finding["fix"] = fix
|
|
67
|
+
return finding
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _row_value(row, key, default=None):
|
|
71
|
+
"""Safely read a sqlite row key with a fallback."""
|
|
72
|
+
try:
|
|
73
|
+
return row[key]
|
|
74
|
+
except Exception:
|
|
75
|
+
return default
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _json_list(value) -> list[str]:
|
|
79
|
+
"""Parse a JSON-encoded list of strings; return [] on malformed input."""
|
|
80
|
+
if not value:
|
|
81
|
+
return []
|
|
82
|
+
try:
|
|
83
|
+
data = json.loads(value)
|
|
84
|
+
except Exception:
|
|
85
|
+
return []
|
|
86
|
+
if not isinstance(data, list):
|
|
87
|
+
return []
|
|
88
|
+
out: list[str] = []
|
|
89
|
+
for item in data:
|
|
90
|
+
if isinstance(item, str):
|
|
91
|
+
out.append(item)
|
|
92
|
+
return out
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _call_leaf(name: str) -> str:
|
|
96
|
+
"""Return the final method/function token from a qualified call name."""
|
|
97
|
+
if not name:
|
|
98
|
+
return ""
|
|
99
|
+
return name.rsplit(".", 1)[-1]
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _dedupe(seq: list[str]) -> list[str]:
|
|
103
|
+
seen: set[str] = set()
|
|
104
|
+
out: list[str] = []
|
|
105
|
+
for s in seq:
|
|
106
|
+
if s and s not in seen:
|
|
107
|
+
seen.add(s)
|
|
108
|
+
out.append(s)
|
|
109
|
+
return out
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def _read_symbol_source(path: str, line_start: int | None, line_end: int | None) -> str:
|
|
113
|
+
"""Best-effort source slice for a symbol location."""
|
|
114
|
+
try:
|
|
115
|
+
with open(path, "r", encoding="utf-8", errors="replace") as f:
|
|
116
|
+
lines = f.read().splitlines()
|
|
117
|
+
except OSError:
|
|
118
|
+
return ""
|
|
119
|
+
if line_start is None or line_end is None:
|
|
120
|
+
return "\n".join(lines)
|
|
121
|
+
ls = max(1, int(line_start))
|
|
122
|
+
le = max(ls, int(line_end))
|
|
123
|
+
return "\n".join(lines[ls - 1 : le])
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _iter_loop_calls(row) -> list[str]:
|
|
127
|
+
"""Return combined loop call names (leaf + qualified)."""
|
|
128
|
+
calls = _json_list(_row_value(row, "calls_in_loops", ""))
|
|
129
|
+
qcalls = _json_list(_row_value(row, "calls_in_loops_qualified", ""))
|
|
130
|
+
return _dedupe(calls + qcalls)
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _call_in(calls: list[str], targets: set[str]) -> list[str]:
|
|
134
|
+
"""Match calls against targets by exact qualified name or leaf token."""
|
|
135
|
+
hits: list[str] = []
|
|
136
|
+
for c in calls:
|
|
137
|
+
if c in targets or _call_leaf(c) in targets:
|
|
138
|
+
hits.append(c)
|
|
139
|
+
return _dedupe(hits)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
_FRAMEWORK_IO_PACKS = {
|
|
143
|
+
"python": [
|
|
144
|
+
{
|
|
145
|
+
"framework": "django-orm",
|
|
146
|
+
"receiver_hints": {"objects", "queryset"},
|
|
147
|
+
"leaves": {"get", "filter", "exclude", "all", "count", "exists"},
|
|
148
|
+
"confidence": "high",
|
|
149
|
+
"fix": ("Batch ORM fetches with `id__in` and add `select_related()/prefetch_related()`."),
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
"framework": "sqlalchemy",
|
|
153
|
+
"receiver_hints": {"session"},
|
|
154
|
+
"leaves": {"execute", "query", "scalars", "get"},
|
|
155
|
+
"confidence": "high",
|
|
156
|
+
"fix": ("Use one `IN` query and eager loading (`selectinload`/`joinedload`) before the loop."),
|
|
157
|
+
},
|
|
158
|
+
],
|
|
159
|
+
"ruby": [
|
|
160
|
+
{
|
|
161
|
+
"framework": "rails-active-record",
|
|
162
|
+
"receiver_hints": {"activerecord", "relation", "model"},
|
|
163
|
+
"leaves": {"find", "find_by", "where", "pluck"},
|
|
164
|
+
"confidence": "high",
|
|
165
|
+
"fix": "Preload associations with `.includes`/`.preload` and fetch in bulk.",
|
|
166
|
+
},
|
|
167
|
+
],
|
|
168
|
+
"php": [
|
|
169
|
+
{
|
|
170
|
+
"framework": "laravel-eloquent",
|
|
171
|
+
"receiver_hints": {"db", "model", "eloquent", "query"},
|
|
172
|
+
"leaves": {"find", "where", "first", "get", "value"},
|
|
173
|
+
"confidence": "high",
|
|
174
|
+
"fix": "Use `Model::whereIn(...)` or eager load with `with(...)`.",
|
|
175
|
+
},
|
|
176
|
+
],
|
|
177
|
+
"javascript": [
|
|
178
|
+
{
|
|
179
|
+
"framework": "node-orm",
|
|
180
|
+
"receiver_hints": {"prisma", "sequelize", "knex", "db"},
|
|
181
|
+
"leaves": {"findmany", "findunique", "findone", "query"},
|
|
182
|
+
"confidence": "high",
|
|
183
|
+
"fix": "Replace per-item ORM calls with one batched query.",
|
|
184
|
+
},
|
|
185
|
+
{
|
|
186
|
+
"framework": "http-client",
|
|
187
|
+
"receiver_hints": {"axios", "fetch", "http", "client"},
|
|
188
|
+
"leaves": {"get", "post", "request"},
|
|
189
|
+
"confidence": "medium",
|
|
190
|
+
"fix": "Use a bulk endpoint or bounded parallel batch requests.",
|
|
191
|
+
},
|
|
192
|
+
],
|
|
193
|
+
"typescript": [
|
|
194
|
+
{
|
|
195
|
+
"framework": "node-orm",
|
|
196
|
+
"receiver_hints": {"prisma", "sequelize", "knex", "db"},
|
|
197
|
+
"leaves": {"findmany", "findunique", "findone", "query"},
|
|
198
|
+
"confidence": "high",
|
|
199
|
+
"fix": "Replace per-item ORM calls with one batched query.",
|
|
200
|
+
},
|
|
201
|
+
{
|
|
202
|
+
"framework": "http-client",
|
|
203
|
+
"receiver_hints": {"axios", "fetch", "http", "client"},
|
|
204
|
+
"leaves": {"get", "post", "request"},
|
|
205
|
+
"confidence": "medium",
|
|
206
|
+
"fix": "Use a bulk endpoint or bounded parallel batch requests.",
|
|
207
|
+
},
|
|
208
|
+
],
|
|
209
|
+
"java": [
|
|
210
|
+
{
|
|
211
|
+
"framework": "jpa-hibernate",
|
|
212
|
+
"receiver_hints": {"repository", "entitymanager", "jdbc", "template"},
|
|
213
|
+
"leaves": {"findbyid", "findall", "query", "execute", "select"},
|
|
214
|
+
"confidence": "high",
|
|
215
|
+
"fix": ("Preload rows with one repository/JPA query (`IN (...)` + fetch join)."),
|
|
216
|
+
},
|
|
217
|
+
],
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def _framework_packs(language: str | None) -> list[dict]:
|
|
222
|
+
if not language:
|
|
223
|
+
return []
|
|
224
|
+
return _FRAMEWORK_IO_PACKS.get(language.lower(), [])
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
_IO_GUARD_HINTS = {
|
|
228
|
+
"python": {
|
|
229
|
+
"select_related(",
|
|
230
|
+
"prefetch_related(",
|
|
231
|
+
"joinedload(",
|
|
232
|
+
"selectinload(",
|
|
233
|
+
"in_(",
|
|
234
|
+
"__in",
|
|
235
|
+
"executemany(",
|
|
236
|
+
},
|
|
237
|
+
"ruby": {
|
|
238
|
+
".includes(",
|
|
239
|
+
".preload(",
|
|
240
|
+
".eager_load(",
|
|
241
|
+
},
|
|
242
|
+
"php": {
|
|
243
|
+
"->with(",
|
|
244
|
+
"wherein(",
|
|
245
|
+
"loadmissing(",
|
|
246
|
+
},
|
|
247
|
+
"javascript": {
|
|
248
|
+
"findmany(",
|
|
249
|
+
"include:",
|
|
250
|
+
" in: ",
|
|
251
|
+
},
|
|
252
|
+
"typescript": {
|
|
253
|
+
"findmany(",
|
|
254
|
+
"include:",
|
|
255
|
+
" in: ",
|
|
256
|
+
},
|
|
257
|
+
"java": {
|
|
258
|
+
"join fetch",
|
|
259
|
+
"findallbyid(",
|
|
260
|
+
" in (",
|
|
261
|
+
},
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
|
|
265
|
+
def _guard_hints_from_source(language: str | None, snippet: str) -> list[str]:
|
|
266
|
+
if not language or not snippet:
|
|
267
|
+
return []
|
|
268
|
+
tokens = _IO_GUARD_HINTS.get((language or "").lower(), set())
|
|
269
|
+
if not tokens:
|
|
270
|
+
return []
|
|
271
|
+
lower = snippet.lower()
|
|
272
|
+
hits: list[str] = []
|
|
273
|
+
for tok in tokens:
|
|
274
|
+
if tok in lower:
|
|
275
|
+
hits.append(tok)
|
|
276
|
+
return _dedupe(hits)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
# ---------------------------------------------------------------------------
|
|
280
|
+
# Individual detectors
|
|
281
|
+
# ---------------------------------------------------------------------------
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def detect_manual_sort(conn):
|
|
285
|
+
"""Symbols named *sort* with nested loops, comparisons, and subscript
|
|
286
|
+
access (swap pattern). No call to built-in sort."""
|
|
287
|
+
rows = conn.execute(
|
|
288
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
289
|
+
"s.line_start, ms.has_nested_loops, ms.calls_in_loops, "
|
|
290
|
+
"ms.loop_with_compare, ms.subscript_in_loops "
|
|
291
|
+
"FROM symbols s "
|
|
292
|
+
"JOIN files f ON s.file_id = f.id "
|
|
293
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
294
|
+
"WHERE (s.name LIKE '%sort%' OR s.name LIKE '%Sort%') "
|
|
295
|
+
"AND s.kind IN ('function', 'method') "
|
|
296
|
+
"AND ms.has_nested_loops = 1 "
|
|
297
|
+
"AND ms.loop_with_compare = 1"
|
|
298
|
+
).fetchall()
|
|
299
|
+
|
|
300
|
+
results = []
|
|
301
|
+
for r in rows:
|
|
302
|
+
if _is_test_path(r["file_path"]):
|
|
303
|
+
continue
|
|
304
|
+
calls = _iter_loop_calls(r)
|
|
305
|
+
if _call_in(calls, {"sort", "sorted", "Arrays.sort", "Collections.sort", "qsort", "std::sort"}):
|
|
306
|
+
continue
|
|
307
|
+
# Subscript access in loops strengthens the signal (swap pattern)
|
|
308
|
+
conf = "high" if r["subscript_in_loops"] else "medium"
|
|
309
|
+
results.append(
|
|
310
|
+
_finding(
|
|
311
|
+
"sorting",
|
|
312
|
+
"manual-sort",
|
|
313
|
+
r,
|
|
314
|
+
"Nested loops with comparisons in sort-named function",
|
|
315
|
+
conf,
|
|
316
|
+
)
|
|
317
|
+
)
|
|
318
|
+
return results
|
|
319
|
+
|
|
320
|
+
|
|
321
|
+
def detect_linear_search(conn):
|
|
322
|
+
"""Functions explicitly named *sorted*/*search_sorted* that loop with
|
|
323
|
+
comparisons but don't call bisect/binarySearch.
|
|
324
|
+
|
|
325
|
+
Downgraded to low confidence because we cannot verify from AST alone
|
|
326
|
+
that the data being searched is actually sorted.
|
|
327
|
+
"""
|
|
328
|
+
rows = conn.execute(
|
|
329
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
330
|
+
"s.line_start, ms.loop_depth, ms.loop_with_compare, ms.calls_in_loops "
|
|
331
|
+
"FROM symbols s "
|
|
332
|
+
"JOIN files f ON s.file_id = f.id "
|
|
333
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
334
|
+
"WHERE (s.name LIKE '%search_sorted%' OR s.name LIKE '%searchSorted%' "
|
|
335
|
+
" OR s.name LIKE '%find_sorted%' OR s.name LIKE '%findSorted%' "
|
|
336
|
+
" OR s.name LIKE '%find_in_sorted%' OR s.name LIKE '%in_sorted%' "
|
|
337
|
+
" OR s.name LIKE '%linear_search%' OR s.name LIKE '%linearSearch%') "
|
|
338
|
+
"AND s.kind IN ('function', 'method') "
|
|
339
|
+
"AND ms.loop_depth >= 1 "
|
|
340
|
+
"AND ms.loop_with_compare = 1"
|
|
341
|
+
).fetchall()
|
|
342
|
+
|
|
343
|
+
results = []
|
|
344
|
+
for r in rows:
|
|
345
|
+
if _is_test_path(r["file_path"]):
|
|
346
|
+
continue
|
|
347
|
+
calls = _iter_loop_calls(r)
|
|
348
|
+
if _call_in(
|
|
349
|
+
calls,
|
|
350
|
+
{
|
|
351
|
+
"bisect",
|
|
352
|
+
"bisect_left",
|
|
353
|
+
"bisect_right",
|
|
354
|
+
"binarySearch",
|
|
355
|
+
"binary_search",
|
|
356
|
+
"lower_bound",
|
|
357
|
+
"upper_bound",
|
|
358
|
+
},
|
|
359
|
+
):
|
|
360
|
+
continue
|
|
361
|
+
results.append(
|
|
362
|
+
_finding(
|
|
363
|
+
"search-sorted",
|
|
364
|
+
"linear-scan",
|
|
365
|
+
r,
|
|
366
|
+
"Linear scan in function that implies sorted data",
|
|
367
|
+
"low",
|
|
368
|
+
)
|
|
369
|
+
)
|
|
370
|
+
return results
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
def detect_list_membership(conn):
|
|
374
|
+
"""Nested loops with equality comparisons — structural pattern for
|
|
375
|
+
O(n^2) membership testing regardless of function name."""
|
|
376
|
+
rows = conn.execute(
|
|
377
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
378
|
+
"s.line_start, ms.loop_with_compare, ms.subscript_in_loops, "
|
|
379
|
+
"ms.has_nested_loops, ms.calls_in_loops "
|
|
380
|
+
"FROM symbols s "
|
|
381
|
+
"JOIN files f ON s.file_id = f.id "
|
|
382
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
383
|
+
"WHERE s.kind IN ('function', 'method') "
|
|
384
|
+
"AND ms.has_nested_loops = 1 "
|
|
385
|
+
"AND ms.loop_with_compare = 1 "
|
|
386
|
+
"AND ms.subscript_in_loops = 1 "
|
|
387
|
+
"AND (s.name LIKE '%contain%' OR s.name LIKE '%member%' "
|
|
388
|
+
" OR s.name LIKE '%exist%' OR s.name LIKE '%has_%' "
|
|
389
|
+
" OR s.name LIKE '%in_%' OR s.name LIKE '%check%' "
|
|
390
|
+
" OR s.name LIKE '%includes%' OR s.name LIKE '%Includes%')"
|
|
391
|
+
).fetchall()
|
|
392
|
+
|
|
393
|
+
results = []
|
|
394
|
+
for r in rows:
|
|
395
|
+
if _is_test_path(r["file_path"]):
|
|
396
|
+
continue
|
|
397
|
+
results.append(
|
|
398
|
+
_finding(
|
|
399
|
+
"membership",
|
|
400
|
+
"list-scan",
|
|
401
|
+
r,
|
|
402
|
+
"Nested loops with comparisons for membership check",
|
|
403
|
+
"medium",
|
|
404
|
+
)
|
|
405
|
+
)
|
|
406
|
+
return results
|
|
407
|
+
|
|
408
|
+
|
|
409
|
+
def detect_string_concat_loop(conn):
|
|
410
|
+
"""Loops with accumulation patterns and string-related call hints.
|
|
411
|
+
|
|
412
|
+
Relies primarily on the structural pattern (loop + accumulator) combined
|
|
413
|
+
with calls to string methods (append/concat) or string-building name hints.
|
|
414
|
+
"""
|
|
415
|
+
rows = conn.execute(
|
|
416
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
417
|
+
"s.line_start, ms.loop_depth, ms.calls_in_loops, ms.loop_with_accumulator "
|
|
418
|
+
"FROM symbols s "
|
|
419
|
+
"JOIN files f ON s.file_id = f.id "
|
|
420
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
421
|
+
"WHERE s.kind IN ('function', 'method') "
|
|
422
|
+
"AND ms.loop_depth >= 1 "
|
|
423
|
+
"AND ms.loop_with_accumulator = 1"
|
|
424
|
+
).fetchall()
|
|
425
|
+
|
|
426
|
+
results = []
|
|
427
|
+
for r in rows:
|
|
428
|
+
if _is_test_path(r["file_path"]):
|
|
429
|
+
continue
|
|
430
|
+
calls = _iter_loop_calls(r)
|
|
431
|
+
# Structural signal: calls to string concat/append methods
|
|
432
|
+
has_concat_call = bool(_call_in(calls, {"concat", "strcat", "append", "push"}))
|
|
433
|
+
# Name signal: function name suggests string building
|
|
434
|
+
name_lower = (r["name"] or "").lower()
|
|
435
|
+
has_name_hint = any(
|
|
436
|
+
kw in name_lower
|
|
437
|
+
for kw in (
|
|
438
|
+
"concat",
|
|
439
|
+
"build_str",
|
|
440
|
+
"build_string",
|
|
441
|
+
"format",
|
|
442
|
+
"render",
|
|
443
|
+
"serialize",
|
|
444
|
+
"to_string",
|
|
445
|
+
"tostring",
|
|
446
|
+
"stringify",
|
|
447
|
+
"to_csv",
|
|
448
|
+
"to_html",
|
|
449
|
+
"to_xml",
|
|
450
|
+
"generate_report",
|
|
451
|
+
"join",
|
|
452
|
+
)
|
|
453
|
+
)
|
|
454
|
+
if has_concat_call or has_name_hint:
|
|
455
|
+
results.append(
|
|
456
|
+
_finding(
|
|
457
|
+
"string-concat",
|
|
458
|
+
"loop-concat",
|
|
459
|
+
r,
|
|
460
|
+
"Loop accumulation in string-building function",
|
|
461
|
+
"medium",
|
|
462
|
+
)
|
|
463
|
+
)
|
|
464
|
+
return results
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def detect_manual_dedup(conn):
|
|
468
|
+
"""Nested loops in dedup/unique-named functions without set usage."""
|
|
469
|
+
rows = conn.execute(
|
|
470
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
471
|
+
"s.line_start, ms.has_nested_loops, ms.loop_with_compare, ms.calls_in_loops "
|
|
472
|
+
"FROM symbols s "
|
|
473
|
+
"JOIN files f ON s.file_id = f.id "
|
|
474
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
475
|
+
"WHERE (s.name LIKE '%dedup%' OR s.name LIKE '%unique%' "
|
|
476
|
+
" OR s.name LIKE '%Dedup%' OR s.name LIKE '%Unique%' "
|
|
477
|
+
" OR s.name LIKE '%distinct%' OR s.name LIKE '%Distinct%' "
|
|
478
|
+
" OR s.name LIKE '%remove_dup%' OR s.name LIKE '%removeDup%') "
|
|
479
|
+
"AND s.kind IN ('function', 'method') "
|
|
480
|
+
"AND ms.has_nested_loops = 1 "
|
|
481
|
+
"AND ms.loop_with_compare = 1"
|
|
482
|
+
).fetchall()
|
|
483
|
+
|
|
484
|
+
results = []
|
|
485
|
+
for r in rows:
|
|
486
|
+
if _is_test_path(r["file_path"]):
|
|
487
|
+
continue
|
|
488
|
+
# Negative check: skip if they already use set/hash
|
|
489
|
+
calls = _iter_loop_calls(r)
|
|
490
|
+
if _call_in(calls, {"set", "Set", "HashSet"}):
|
|
491
|
+
continue
|
|
492
|
+
results.append(
|
|
493
|
+
_finding(
|
|
494
|
+
"unique",
|
|
495
|
+
"nested-dedup",
|
|
496
|
+
r,
|
|
497
|
+
"Nested loops with comparisons in dedup function",
|
|
498
|
+
"high",
|
|
499
|
+
)
|
|
500
|
+
)
|
|
501
|
+
return results
|
|
502
|
+
|
|
503
|
+
|
|
504
|
+
def detect_manual_maxmin(conn):
|
|
505
|
+
"""Loops with comparisons in max/min-named functions.
|
|
506
|
+
|
|
507
|
+
Same Big-O (both O(n)) — this is an idiom improvement, flagged at low
|
|
508
|
+
confidence.
|
|
509
|
+
"""
|
|
510
|
+
rows = conn.execute(
|
|
511
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
512
|
+
"s.line_start, ms.loop_depth, ms.loop_with_compare, "
|
|
513
|
+
"ms.loop_with_accumulator, ms.calls_in_loops "
|
|
514
|
+
"FROM symbols s "
|
|
515
|
+
"JOIN files f ON s.file_id = f.id "
|
|
516
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
517
|
+
"WHERE (s.name LIKE '%find_max%' OR s.name LIKE '%find_min%' "
|
|
518
|
+
" OR s.name LIKE '%findMax%' OR s.name LIKE '%findMin%' "
|
|
519
|
+
" OR s.name LIKE '%get_max%' OR s.name LIKE '%get_min%' "
|
|
520
|
+
" OR s.name LIKE '%getMax%' OR s.name LIKE '%getMin%' "
|
|
521
|
+
" OR s.name LIKE '%find_largest%' OR s.name LIKE '%find_smallest%' "
|
|
522
|
+
" OR s.name LIKE '%findLargest%' OR s.name LIKE '%findSmallest%') "
|
|
523
|
+
"AND s.kind IN ('function', 'method') "
|
|
524
|
+
"AND ms.loop_depth >= 1 "
|
|
525
|
+
"AND ms.loop_with_compare = 1"
|
|
526
|
+
).fetchall()
|
|
527
|
+
|
|
528
|
+
results = []
|
|
529
|
+
for r in rows:
|
|
530
|
+
if _is_test_path(r["file_path"]):
|
|
531
|
+
continue
|
|
532
|
+
calls = _iter_loop_calls(r)
|
|
533
|
+
if _call_in(calls, {"max", "min", "Math.max", "Math.min", "Collections.max", "Collections.min"}):
|
|
534
|
+
continue
|
|
535
|
+
results.append(
|
|
536
|
+
_finding(
|
|
537
|
+
"max-min",
|
|
538
|
+
"manual-loop",
|
|
539
|
+
r,
|
|
540
|
+
"Manual loop with comparisons in max/min function (idiomatic improvement)",
|
|
541
|
+
"low",
|
|
542
|
+
)
|
|
543
|
+
)
|
|
544
|
+
return results
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def detect_manual_accumulation(conn):
|
|
548
|
+
"""Loops with accumulator in sum/total-named functions.
|
|
549
|
+
|
|
550
|
+
Same Big-O (both O(n)) — idiom improvement, flagged at low confidence.
|
|
551
|
+
"""
|
|
552
|
+
rows = conn.execute(
|
|
553
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
554
|
+
"s.line_start, ms.loop_depth, ms.loop_with_accumulator, ms.calls_in_loops "
|
|
555
|
+
"FROM symbols s "
|
|
556
|
+
"JOIN files f ON s.file_id = f.id "
|
|
557
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
558
|
+
"WHERE (s.name LIKE '%_sum%' OR s.name LIKE '%_total%' "
|
|
559
|
+
" OR s.name LIKE '%Sum%' OR s.name LIKE '%Total%' "
|
|
560
|
+
" OR s.name LIKE '%accumulate%' OR s.name LIKE '%Accumulate%') "
|
|
561
|
+
"AND s.kind IN ('function', 'method') "
|
|
562
|
+
"AND ms.loop_depth >= 1 "
|
|
563
|
+
"AND ms.loop_with_accumulator = 1"
|
|
564
|
+
).fetchall()
|
|
565
|
+
|
|
566
|
+
results = []
|
|
567
|
+
for r in rows:
|
|
568
|
+
if _is_test_path(r["file_path"]):
|
|
569
|
+
continue
|
|
570
|
+
calls = _iter_loop_calls(r)
|
|
571
|
+
if _call_in(calls, {"sum", "reduce", "aggregate", "prod"}):
|
|
572
|
+
continue
|
|
573
|
+
results.append(
|
|
574
|
+
_finding(
|
|
575
|
+
"accumulation",
|
|
576
|
+
"manual-sum",
|
|
577
|
+
r,
|
|
578
|
+
"Loop with accumulator in sum/total function (idiomatic improvement)",
|
|
579
|
+
"low",
|
|
580
|
+
)
|
|
581
|
+
)
|
|
582
|
+
return results
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def detect_manual_power(conn):
|
|
586
|
+
"""Loop-based exponentiation in power/exponent-named functions."""
|
|
587
|
+
try:
|
|
588
|
+
rows = conn.execute(
|
|
589
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
590
|
+
"s.line_start, ms.loop_depth, ms.loop_with_multiplication, "
|
|
591
|
+
"ms.calls_in_loops, ms.calls_in_loops_qualified "
|
|
592
|
+
"FROM symbols s "
|
|
593
|
+
"JOIN files f ON s.file_id = f.id "
|
|
594
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
595
|
+
"WHERE (s.name LIKE '%pow%' OR s.name LIKE '%Pow%' "
|
|
596
|
+
" OR s.name LIKE '%power%' OR s.name LIKE '%Power%' "
|
|
597
|
+
" OR s.name LIKE '%exp%' OR s.name LIKE '%Exponent%') "
|
|
598
|
+
"AND s.kind IN ('function', 'method') "
|
|
599
|
+
"AND ms.loop_depth >= 1 "
|
|
600
|
+
"AND ms.loop_with_multiplication = 1"
|
|
601
|
+
).fetchall()
|
|
602
|
+
except Exception:
|
|
603
|
+
rows = conn.execute(
|
|
604
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
605
|
+
"s.line_start, ms.loop_depth, 0 as loop_with_multiplication, "
|
|
606
|
+
"ms.calls_in_loops, '' as calls_in_loops_qualified "
|
|
607
|
+
"FROM symbols s "
|
|
608
|
+
"JOIN files f ON s.file_id = f.id "
|
|
609
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
610
|
+
"WHERE (s.name LIKE '%pow%' OR s.name LIKE '%Pow%' "
|
|
611
|
+
" OR s.name LIKE '%power%' OR s.name LIKE '%Power%' "
|
|
612
|
+
" OR s.name LIKE '%exp%' OR s.name LIKE '%Exponent%') "
|
|
613
|
+
"AND s.kind IN ('function', 'method') "
|
|
614
|
+
"AND ms.loop_depth >= 1 "
|
|
615
|
+
"AND ms.loop_with_accumulator = 1"
|
|
616
|
+
).fetchall()
|
|
617
|
+
|
|
618
|
+
results = []
|
|
619
|
+
for r in rows:
|
|
620
|
+
if _is_test_path(r["file_path"]):
|
|
621
|
+
continue
|
|
622
|
+
calls = _iter_loop_calls(r)
|
|
623
|
+
if _call_in(calls, {"pow", "Math.pow", "std::pow", "math.pow", "BigInteger.modPow"}):
|
|
624
|
+
continue
|
|
625
|
+
conf = "high" if _row_value(r, "loop_with_multiplication", 0) else "medium"
|
|
626
|
+
results.append(
|
|
627
|
+
_finding(
|
|
628
|
+
"manual-power",
|
|
629
|
+
"loop-multiply",
|
|
630
|
+
r,
|
|
631
|
+
"Loop multiplication used for exponentiation",
|
|
632
|
+
conf,
|
|
633
|
+
)
|
|
634
|
+
)
|
|
635
|
+
return results
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def detect_manual_gcd(conn):
|
|
639
|
+
"""Manual GCD loops where built-in/standard helpers are available."""
|
|
640
|
+
try:
|
|
641
|
+
rows = conn.execute(
|
|
642
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
643
|
+
"s.line_start, ms.loop_depth, ms.loop_with_modulo, "
|
|
644
|
+
"ms.calls_in_loops, ms.calls_in_loops_qualified "
|
|
645
|
+
"FROM symbols s "
|
|
646
|
+
"JOIN files f ON s.file_id = f.id "
|
|
647
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
648
|
+
"WHERE (s.name LIKE '%gcd%' OR s.name LIKE '%GCD%' "
|
|
649
|
+
" OR s.name LIKE '%hcf%' OR s.name LIKE '%gcf%') "
|
|
650
|
+
"AND s.kind IN ('function', 'method') "
|
|
651
|
+
"AND ms.loop_depth >= 1"
|
|
652
|
+
).fetchall()
|
|
653
|
+
except Exception:
|
|
654
|
+
rows = conn.execute(
|
|
655
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
656
|
+
"s.line_start, ms.loop_depth, 0 as loop_with_modulo, "
|
|
657
|
+
"ms.calls_in_loops, '' as calls_in_loops_qualified "
|
|
658
|
+
"FROM symbols s "
|
|
659
|
+
"JOIN files f ON s.file_id = f.id "
|
|
660
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
661
|
+
"WHERE (s.name LIKE '%gcd%' OR s.name LIKE '%GCD%' "
|
|
662
|
+
" OR s.name LIKE '%hcf%' OR s.name LIKE '%gcf%') "
|
|
663
|
+
"AND s.kind IN ('function', 'method') "
|
|
664
|
+
"AND ms.loop_depth >= 1"
|
|
665
|
+
).fetchall()
|
|
666
|
+
|
|
667
|
+
results = []
|
|
668
|
+
for r in rows:
|
|
669
|
+
if _is_test_path(r["file_path"]):
|
|
670
|
+
continue
|
|
671
|
+
calls = _iter_loop_calls(r)
|
|
672
|
+
if _call_in(calls, {"gcd", "math.gcd", "std::gcd", "BigInteger.gcd"}):
|
|
673
|
+
continue
|
|
674
|
+
conf = "medium"
|
|
675
|
+
if _row_value(r, "loop_with_modulo", 0):
|
|
676
|
+
conf = "high"
|
|
677
|
+
results.append(
|
|
678
|
+
_finding(
|
|
679
|
+
"manual-gcd",
|
|
680
|
+
"manual-gcd",
|
|
681
|
+
r,
|
|
682
|
+
"Manual GCD loop can be replaced with standard gcd helper",
|
|
683
|
+
conf,
|
|
684
|
+
)
|
|
685
|
+
)
|
|
686
|
+
return results
|
|
687
|
+
|
|
688
|
+
|
|
689
|
+
def detect_string_reverse(conn):
|
|
690
|
+
"""Manual reversal loops in reverse-named functions."""
|
|
691
|
+
try:
|
|
692
|
+
rows = conn.execute(
|
|
693
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
694
|
+
"s.line_start, ms.loop_depth, ms.loop_with_accumulator, "
|
|
695
|
+
"ms.calls_in_loops, ms.calls_in_loops_qualified "
|
|
696
|
+
"FROM symbols s "
|
|
697
|
+
"JOIN files f ON s.file_id = f.id "
|
|
698
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
699
|
+
"WHERE (s.name LIKE '%reverse%' OR s.name LIKE '%Reverse%') "
|
|
700
|
+
"AND s.kind IN ('function', 'method') "
|
|
701
|
+
"AND ms.loop_depth >= 1"
|
|
702
|
+
).fetchall()
|
|
703
|
+
except Exception:
|
|
704
|
+
rows = conn.execute(
|
|
705
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
706
|
+
"s.line_start, ms.loop_depth, ms.loop_with_accumulator, "
|
|
707
|
+
"ms.calls_in_loops, '' as calls_in_loops_qualified "
|
|
708
|
+
"FROM symbols s "
|
|
709
|
+
"JOIN files f ON s.file_id = f.id "
|
|
710
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
711
|
+
"WHERE (s.name LIKE '%reverse%' OR s.name LIKE '%Reverse%') "
|
|
712
|
+
"AND s.kind IN ('function', 'method') "
|
|
713
|
+
"AND ms.loop_depth >= 1"
|
|
714
|
+
).fetchall()
|
|
715
|
+
|
|
716
|
+
results = []
|
|
717
|
+
for r in rows:
|
|
718
|
+
if _is_test_path(r["file_path"]):
|
|
719
|
+
continue
|
|
720
|
+
calls = _iter_loop_calls(r)
|
|
721
|
+
if _call_in(calls, {"reverse", "reversed", "std::reverse", "StringBuilder.reverse", "strrev"}):
|
|
722
|
+
continue
|
|
723
|
+
results.append(
|
|
724
|
+
_finding(
|
|
725
|
+
"string-reverse",
|
|
726
|
+
"manual-reverse",
|
|
727
|
+
r,
|
|
728
|
+
"Manual character-loop reversal in reverse-named function",
|
|
729
|
+
"low",
|
|
730
|
+
)
|
|
731
|
+
)
|
|
732
|
+
return results
|
|
733
|
+
|
|
734
|
+
|
|
735
|
+
def detect_matrix_mult(conn):
|
|
736
|
+
"""Naive triple-loop matrix multiplication patterns."""
|
|
737
|
+
try:
|
|
738
|
+
rows = conn.execute(
|
|
739
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
740
|
+
"s.line_start, ms.loop_depth, ms.subscript_in_loops, "
|
|
741
|
+
"ms.loop_with_multiplication, ms.loop_with_accumulator, "
|
|
742
|
+
"ms.calls_in_loops, ms.calls_in_loops_qualified "
|
|
743
|
+
"FROM symbols s "
|
|
744
|
+
"JOIN files f ON s.file_id = f.id "
|
|
745
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
746
|
+
"WHERE (s.name LIKE '%matrix%' OR s.name LIKE '%matmul%' "
|
|
747
|
+
" OR s.name LIKE '%multiply_matrix%' OR s.name LIKE '%dot%') "
|
|
748
|
+
"AND s.kind IN ('function', 'method') "
|
|
749
|
+
"AND ms.loop_depth >= 3 "
|
|
750
|
+
"AND ms.subscript_in_loops = 1"
|
|
751
|
+
).fetchall()
|
|
752
|
+
except Exception:
|
|
753
|
+
rows = conn.execute(
|
|
754
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
755
|
+
"s.line_start, ms.loop_depth, ms.subscript_in_loops, "
|
|
756
|
+
"0 as loop_with_multiplication, ms.loop_with_accumulator, "
|
|
757
|
+
"ms.calls_in_loops, '' as calls_in_loops_qualified "
|
|
758
|
+
"FROM symbols s "
|
|
759
|
+
"JOIN files f ON s.file_id = f.id "
|
|
760
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
761
|
+
"WHERE (s.name LIKE '%matrix%' OR s.name LIKE '%matmul%' "
|
|
762
|
+
" OR s.name LIKE '%multiply_matrix%' OR s.name LIKE '%dot%') "
|
|
763
|
+
"AND s.kind IN ('function', 'method') "
|
|
764
|
+
"AND ms.loop_depth >= 3 "
|
|
765
|
+
"AND ms.subscript_in_loops = 1"
|
|
766
|
+
).fetchall()
|
|
767
|
+
|
|
768
|
+
results = []
|
|
769
|
+
for r in rows:
|
|
770
|
+
if _is_test_path(r["file_path"]):
|
|
771
|
+
continue
|
|
772
|
+
calls = _iter_loop_calls(r)
|
|
773
|
+
if _call_in(calls, {"dot", "matmul", "gemm", "dgemm", "numpy.dot", "np.matmul"}):
|
|
774
|
+
continue
|
|
775
|
+
conf = (
|
|
776
|
+
"high"
|
|
777
|
+
if (_row_value(r, "loop_with_multiplication", 0) and _row_value(r, "loop_with_accumulator", 0))
|
|
778
|
+
else "medium"
|
|
779
|
+
)
|
|
780
|
+
results.append(
|
|
781
|
+
_finding(
|
|
782
|
+
"matrix-mult",
|
|
783
|
+
"naive-triple",
|
|
784
|
+
r,
|
|
785
|
+
"Naive matrix multiplication via nested loops",
|
|
786
|
+
conf,
|
|
787
|
+
)
|
|
788
|
+
)
|
|
789
|
+
return results
|
|
790
|
+
|
|
791
|
+
|
|
792
|
+
def detect_naive_fibonacci(conn):
|
|
793
|
+
"""Recursive functions named *fib* without memoization.
|
|
794
|
+
|
|
795
|
+
O(2^n) -> O(n) — one of the strongest algorithmic improvements.
|
|
796
|
+
"""
|
|
797
|
+
rows = conn.execute(
|
|
798
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
799
|
+
"s.line_start, ms.has_self_call "
|
|
800
|
+
"FROM symbols s "
|
|
801
|
+
"JOIN files f ON s.file_id = f.id "
|
|
802
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
803
|
+
"WHERE (s.name LIKE '%fib%' OR s.name LIKE '%Fib%') "
|
|
804
|
+
"AND s.kind IN ('function', 'method') "
|
|
805
|
+
"AND ms.has_self_call >= 1"
|
|
806
|
+
).fetchall()
|
|
807
|
+
|
|
808
|
+
results = []
|
|
809
|
+
for r in rows:
|
|
810
|
+
if _is_test_path(r["file_path"]):
|
|
811
|
+
continue
|
|
812
|
+
# Check if there's a memoization decorator (edge to lru_cache/cache)
|
|
813
|
+
memo_edge = conn.execute(
|
|
814
|
+
"SELECT 1 FROM edges e "
|
|
815
|
+
"JOIN symbols t ON e.target_id = t.id "
|
|
816
|
+
"WHERE e.source_id = ? "
|
|
817
|
+
"AND t.name IN ('lru_cache', 'cache', 'memoize', 'memo', "
|
|
818
|
+
" 'functools.lru_cache', 'functools.cache') "
|
|
819
|
+
"LIMIT 1",
|
|
820
|
+
(r["id"],),
|
|
821
|
+
).fetchone()
|
|
822
|
+
if memo_edge:
|
|
823
|
+
continue
|
|
824
|
+
results.append(
|
|
825
|
+
_finding(
|
|
826
|
+
"fibonacci",
|
|
827
|
+
"naive-recursive",
|
|
828
|
+
r,
|
|
829
|
+
"Recursive fibonacci without memoization (exponential blowup)",
|
|
830
|
+
"high",
|
|
831
|
+
)
|
|
832
|
+
)
|
|
833
|
+
return results
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def detect_nested_lookup(conn):
|
|
837
|
+
"""Nested loops with subscript access and comparisons — O(n*m) lookup.
|
|
838
|
+
|
|
839
|
+
Suppresses known false positives: grid/matrix traversal (name hints),
|
|
840
|
+
and requires both nested loops AND comparisons (not just nested loops
|
|
841
|
+
with subscript access, which could be matrix operations).
|
|
842
|
+
"""
|
|
843
|
+
rows = conn.execute(
|
|
844
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
845
|
+
"s.line_start, ms.has_nested_loops, ms.subscript_in_loops, "
|
|
846
|
+
"ms.loop_with_compare "
|
|
847
|
+
"FROM symbols s "
|
|
848
|
+
"JOIN files f ON s.file_id = f.id "
|
|
849
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
850
|
+
"JOIN symbol_metrics sm ON sm.symbol_id = s.id "
|
|
851
|
+
"WHERE s.kind IN ('function', 'method') "
|
|
852
|
+
"AND ms.has_nested_loops = 1 "
|
|
853
|
+
"AND ms.subscript_in_loops = 1 "
|
|
854
|
+
"AND ms.loop_with_compare = 1 "
|
|
855
|
+
"AND sm.cognitive_complexity >= 8"
|
|
856
|
+
).fetchall()
|
|
857
|
+
|
|
858
|
+
# Names that suggest grid/matrix traversal (suppress these)
|
|
859
|
+
_GRID_NAMES = {
|
|
860
|
+
"matrix",
|
|
861
|
+
"grid",
|
|
862
|
+
"board",
|
|
863
|
+
"pixel",
|
|
864
|
+
"cell",
|
|
865
|
+
"permut",
|
|
866
|
+
"combin",
|
|
867
|
+
"cartesian",
|
|
868
|
+
"product",
|
|
869
|
+
"transpose",
|
|
870
|
+
"rotate",
|
|
871
|
+
"convolv",
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
results = []
|
|
875
|
+
for r in rows:
|
|
876
|
+
if _is_test_path(r["file_path"]):
|
|
877
|
+
continue
|
|
878
|
+
# Suppress grid/matrix traversal patterns
|
|
879
|
+
name_lower = (r["name"] or "").lower()
|
|
880
|
+
if any(kw in name_lower for kw in _GRID_NAMES):
|
|
881
|
+
continue
|
|
882
|
+
results.append(
|
|
883
|
+
_finding(
|
|
884
|
+
"nested-lookup",
|
|
885
|
+
"nested-iteration",
|
|
886
|
+
r,
|
|
887
|
+
"Nested loops with subscript access and comparisons (potential O(n*m))",
|
|
888
|
+
"medium",
|
|
889
|
+
)
|
|
890
|
+
)
|
|
891
|
+
return results
|
|
892
|
+
|
|
893
|
+
|
|
894
|
+
def detect_manual_groupby(conn):
|
|
895
|
+
"""Loops in group/categorize-named functions without defaultdict/groupby.
|
|
896
|
+
|
|
897
|
+
Same Big-O (both O(n)) — idiom improvement.
|
|
898
|
+
"""
|
|
899
|
+
rows = conn.execute(
|
|
900
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
901
|
+
"s.line_start, ms.loop_depth, ms.loop_with_accumulator, ms.calls_in_loops "
|
|
902
|
+
"FROM symbols s "
|
|
903
|
+
"JOIN files f ON s.file_id = f.id "
|
|
904
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
905
|
+
"WHERE (s.name LIKE '%group%' OR s.name LIKE '%Group%' "
|
|
906
|
+
" OR s.name LIKE '%bucket%' OR s.name LIKE '%Bucket%' "
|
|
907
|
+
" OR s.name LIKE '%partition%' OR s.name LIKE '%Partition%' "
|
|
908
|
+
" OR s.name LIKE '%categorize%' OR s.name LIKE '%Categorize%' "
|
|
909
|
+
" OR s.name LIKE '%classify%' OR s.name LIKE '%Classify%' "
|
|
910
|
+
" OR s.name LIKE '%bin_by%' OR s.name LIKE '%key_by%' "
|
|
911
|
+
" OR s.name LIKE '%index_by%') "
|
|
912
|
+
"AND s.kind IN ('function', 'method') "
|
|
913
|
+
"AND ms.loop_depth >= 1"
|
|
914
|
+
).fetchall()
|
|
915
|
+
|
|
916
|
+
results = []
|
|
917
|
+
for r in rows:
|
|
918
|
+
if _is_test_path(r["file_path"]):
|
|
919
|
+
continue
|
|
920
|
+
calls = _iter_loop_calls(r)
|
|
921
|
+
if _call_in(calls, {"groupby", "group_by", "defaultdict", "setdefault", "groupingBy", "Collectors"}):
|
|
922
|
+
continue
|
|
923
|
+
results.append(
|
|
924
|
+
_finding(
|
|
925
|
+
"groupby",
|
|
926
|
+
"manual-check",
|
|
927
|
+
r,
|
|
928
|
+
"Manual loop in group-by function (idiomatic improvement)",
|
|
929
|
+
"low",
|
|
930
|
+
)
|
|
931
|
+
)
|
|
932
|
+
return results
|
|
933
|
+
|
|
934
|
+
|
|
935
|
+
def detect_busy_wait(conn):
|
|
936
|
+
"""Loops that call sleep — polling / busy-wait pattern.
|
|
937
|
+
|
|
938
|
+
Suppresses intentional polling: functions named *poll*, *retry*,
|
|
939
|
+
*health_check*, *monitor*, *wait_for* — these are legitimate patterns.
|
|
940
|
+
"""
|
|
941
|
+
rows = conn.execute(
|
|
942
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
943
|
+
"s.line_start, ms.loop_depth, ms.calls_in_loops "
|
|
944
|
+
"FROM symbols s "
|
|
945
|
+
"JOIN files f ON s.file_id = f.id "
|
|
946
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
947
|
+
"WHERE s.kind IN ('function', 'method') "
|
|
948
|
+
"AND ms.loop_depth >= 1"
|
|
949
|
+
).fetchall()
|
|
950
|
+
|
|
951
|
+
# Intentional polling patterns — suppress these
|
|
952
|
+
_POLL_NAMES = {
|
|
953
|
+
"poll",
|
|
954
|
+
"retry",
|
|
955
|
+
"health_check",
|
|
956
|
+
"healthcheck",
|
|
957
|
+
"monitor",
|
|
958
|
+
"wait_for",
|
|
959
|
+
"wait_until",
|
|
960
|
+
"watchdog",
|
|
961
|
+
"ping",
|
|
962
|
+
"heartbeat",
|
|
963
|
+
"keepalive",
|
|
964
|
+
"backoff",
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
results = []
|
|
968
|
+
for r in rows:
|
|
969
|
+
if _is_test_path(r["file_path"]):
|
|
970
|
+
continue
|
|
971
|
+
calls = _iter_loop_calls(r)
|
|
972
|
+
if not _call_in(calls, {"sleep", "time.sleep", "Thread.sleep", "usleep", "nanosleep", "Sleep"}):
|
|
973
|
+
continue
|
|
974
|
+
# Suppress intentional polling
|
|
975
|
+
name_lower = (r["name"] or "").lower()
|
|
976
|
+
if any(kw in name_lower for kw in _POLL_NAMES):
|
|
977
|
+
continue
|
|
978
|
+
results.append(
|
|
979
|
+
_finding(
|
|
980
|
+
"busy-wait",
|
|
981
|
+
"sleep-loop",
|
|
982
|
+
r,
|
|
983
|
+
"sleep() called inside a loop (busy-wait pattern)",
|
|
984
|
+
"high",
|
|
985
|
+
)
|
|
986
|
+
)
|
|
987
|
+
return results
|
|
988
|
+
|
|
989
|
+
|
|
990
|
+
# ---------------------------------------------------------------------------
|
|
991
|
+
# New detectors: patterns identified by research
|
|
992
|
+
# ---------------------------------------------------------------------------
|
|
993
|
+
|
|
994
|
+
|
|
995
|
+
def detect_regex_in_loop(conn):
|
|
996
|
+
"""Regex compilation inside a loop — recompiles on every iteration.
|
|
997
|
+
|
|
998
|
+
O(n*p) wasted compilation when O(p + n*m) is achievable by compiling
|
|
999
|
+
once outside the loop. Applies to all languages with regex engines.
|
|
1000
|
+
"""
|
|
1001
|
+
rows = conn.execute(
|
|
1002
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
1003
|
+
"s.line_start, ms.loop_depth, ms.calls_in_loops "
|
|
1004
|
+
"FROM symbols s "
|
|
1005
|
+
"JOIN files f ON s.file_id = f.id "
|
|
1006
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
1007
|
+
"WHERE s.kind IN ('function', 'method') "
|
|
1008
|
+
"AND ms.loop_depth >= 1"
|
|
1009
|
+
).fetchall()
|
|
1010
|
+
|
|
1011
|
+
# Note: call target names are extracted as the last identifier in
|
|
1012
|
+
# member expressions (e.g. re.compile -> "compile", re.match -> "match")
|
|
1013
|
+
_REGEX_COMPILE_CALLS = {"compile", "Compile", "MustCompile"}
|
|
1014
|
+
_REGEX_CONVENIENCE_CALLS = {
|
|
1015
|
+
"match",
|
|
1016
|
+
"search",
|
|
1017
|
+
"findall",
|
|
1018
|
+
"sub",
|
|
1019
|
+
"split",
|
|
1020
|
+
"fullmatch",
|
|
1021
|
+
"finditer",
|
|
1022
|
+
"matches",
|
|
1023
|
+
"Replace",
|
|
1024
|
+
"ReplaceAll",
|
|
1025
|
+
"Find",
|
|
1026
|
+
"FindAll",
|
|
1027
|
+
"MatchString",
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
results = []
|
|
1031
|
+
for r in rows:
|
|
1032
|
+
if _is_test_path(r["file_path"]):
|
|
1033
|
+
continue
|
|
1034
|
+
calls = _iter_loop_calls(r)
|
|
1035
|
+
# Direct compile in loop is always bad
|
|
1036
|
+
compile_calls = _call_in(calls, _REGEX_COMPILE_CALLS)
|
|
1037
|
+
# Convenience regex calls in loop (re.match, re.search, etc.) also
|
|
1038
|
+
# compile each time in most runtimes — flag at medium confidence
|
|
1039
|
+
# since these could be on a pre-compiled pattern object
|
|
1040
|
+
convenience_calls = _call_in(calls, _REGEX_CONVENIENCE_CALLS)
|
|
1041
|
+
if compile_calls:
|
|
1042
|
+
results.append(
|
|
1043
|
+
_finding(
|
|
1044
|
+
"regex-in-loop",
|
|
1045
|
+
"compile-per-iter",
|
|
1046
|
+
r,
|
|
1047
|
+
f"Regex compile ({', '.join(compile_calls[:2])}) inside loop",
|
|
1048
|
+
"high",
|
|
1049
|
+
)
|
|
1050
|
+
)
|
|
1051
|
+
elif convenience_calls:
|
|
1052
|
+
results.append(
|
|
1053
|
+
_finding(
|
|
1054
|
+
"regex-in-loop",
|
|
1055
|
+
"compile-per-iter",
|
|
1056
|
+
r,
|
|
1057
|
+
f"Regex call ({', '.join(convenience_calls[:2])}) inside loop (may recompile per iteration)",
|
|
1058
|
+
"medium",
|
|
1059
|
+
)
|
|
1060
|
+
)
|
|
1061
|
+
return results
|
|
1062
|
+
|
|
1063
|
+
|
|
1064
|
+
def detect_io_in_loop(conn):
|
|
1065
|
+
"""Database query, HTTP request, or file I/O inside a loop — N+1 pattern.
|
|
1066
|
+
|
|
1067
|
+
One of the most impactful performance anti-patterns in web applications.
|
|
1068
|
+
Each iteration incurs a full I/O round trip.
|
|
1069
|
+
"""
|
|
1070
|
+
try:
|
|
1071
|
+
rows = conn.execute(
|
|
1072
|
+
"SELECT s.id, s.file_id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
1073
|
+
"f.language as language, s.line_start, s.line_end, ms.loop_depth, ms.calls_in_loops, "
|
|
1074
|
+
"ms.calls_in_loops_qualified "
|
|
1075
|
+
"FROM symbols s "
|
|
1076
|
+
"JOIN files f ON s.file_id = f.id "
|
|
1077
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
1078
|
+
"WHERE s.kind IN ('function', 'method') "
|
|
1079
|
+
"AND ms.loop_depth >= 1"
|
|
1080
|
+
).fetchall()
|
|
1081
|
+
except Exception:
|
|
1082
|
+
rows = conn.execute(
|
|
1083
|
+
"SELECT s.id, s.file_id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
1084
|
+
"f.language as language, s.line_start, s.line_end, ms.loop_depth, ms.calls_in_loops, "
|
|
1085
|
+
"'' as calls_in_loops_qualified "
|
|
1086
|
+
"FROM symbols s "
|
|
1087
|
+
"JOIN files f ON s.file_id = f.id "
|
|
1088
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
1089
|
+
"WHERE s.kind IN ('function', 'method') "
|
|
1090
|
+
"AND ms.loop_depth >= 1"
|
|
1091
|
+
).fetchall()
|
|
1092
|
+
|
|
1093
|
+
# High-confidence calls: strongly indicative DB/API round trips.
|
|
1094
|
+
_HIGH_EXACT = {
|
|
1095
|
+
"requests.get",
|
|
1096
|
+
"requests.post",
|
|
1097
|
+
"requests.put",
|
|
1098
|
+
"requests.delete",
|
|
1099
|
+
"requests.patch",
|
|
1100
|
+
"urllib.request.urlopen",
|
|
1101
|
+
"session.execute",
|
|
1102
|
+
"session.query",
|
|
1103
|
+
"cursor.execute",
|
|
1104
|
+
"http.Get",
|
|
1105
|
+
"http.Post",
|
|
1106
|
+
}
|
|
1107
|
+
_HIGH_EXACT_LOWER = {c.lower() for c in _HIGH_EXACT}
|
|
1108
|
+
_HIGH_LEAF = {"execute", "executemany", "query", "urlopen"}
|
|
1109
|
+
_AMBIGUOUS_BARE = {"query", "find", "get"}
|
|
1110
|
+
_MEDIUM_LEAF = {"fetchone", "fetchall", "fetchmany", "fetch", "find", "get", "open"}
|
|
1111
|
+
_IO_RECEIVER_HINTS = {
|
|
1112
|
+
"session",
|
|
1113
|
+
"cursor",
|
|
1114
|
+
"db",
|
|
1115
|
+
"conn",
|
|
1116
|
+
"connection",
|
|
1117
|
+
"repo",
|
|
1118
|
+
"repository",
|
|
1119
|
+
"queryset",
|
|
1120
|
+
"client",
|
|
1121
|
+
"api",
|
|
1122
|
+
"http",
|
|
1123
|
+
"requests",
|
|
1124
|
+
"urllib",
|
|
1125
|
+
}
|
|
1126
|
+
|
|
1127
|
+
# Suppress functions that are intentionally batch/migration wrappers.
|
|
1128
|
+
_IO_WRAPPER_NAMES = {
|
|
1129
|
+
"batch",
|
|
1130
|
+
"bulk",
|
|
1131
|
+
"migrate",
|
|
1132
|
+
"seed",
|
|
1133
|
+
"import",
|
|
1134
|
+
"export",
|
|
1135
|
+
"sync_all",
|
|
1136
|
+
"backfill",
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
def _receiver_hint(call: str) -> str:
|
|
1140
|
+
if "." not in call:
|
|
1141
|
+
return ""
|
|
1142
|
+
return call.rsplit(".", 1)[0].lower()
|
|
1143
|
+
|
|
1144
|
+
def _receiver_is_ioish(call: str) -> bool:
|
|
1145
|
+
recv = _receiver_hint(call)
|
|
1146
|
+
if not recv:
|
|
1147
|
+
return False
|
|
1148
|
+
return any(h in recv for h in _IO_RECEIVER_HINTS)
|
|
1149
|
+
|
|
1150
|
+
def _match_framework_pack(call: str, language: str | None) -> dict | None:
|
|
1151
|
+
leaf = _call_leaf(call).lower()
|
|
1152
|
+
recv = _receiver_hint(call)
|
|
1153
|
+
lower_c = call.lower()
|
|
1154
|
+
for pack in _framework_packs(language):
|
|
1155
|
+
leaves = pack.get("leaves", set())
|
|
1156
|
+
recv_hints = pack.get("receiver_hints", set())
|
|
1157
|
+
if lower_c in {c.lower() for c in pack.get("exact", set())}:
|
|
1158
|
+
return pack
|
|
1159
|
+
if leaf not in leaves:
|
|
1160
|
+
continue
|
|
1161
|
+
if not recv_hints:
|
|
1162
|
+
return pack
|
|
1163
|
+
if any(h in recv for h in recv_hints):
|
|
1164
|
+
return pack
|
|
1165
|
+
return None
|
|
1166
|
+
|
|
1167
|
+
results = []
|
|
1168
|
+
for r in rows:
|
|
1169
|
+
if _is_test_path(r["file_path"]):
|
|
1170
|
+
continue
|
|
1171
|
+
language = _row_value(r, "language", "")
|
|
1172
|
+
snippet = _read_symbol_source(
|
|
1173
|
+
r["file_path"],
|
|
1174
|
+
_row_value(r, "line_start", None),
|
|
1175
|
+
_row_value(r, "line_end", None),
|
|
1176
|
+
)
|
|
1177
|
+
guard_hints = _guard_hints_from_source(language, snippet)
|
|
1178
|
+
calls = _iter_loop_calls(r)
|
|
1179
|
+
if not calls:
|
|
1180
|
+
continue
|
|
1181
|
+
|
|
1182
|
+
high_calls: list[str] = []
|
|
1183
|
+
medium_calls: list[str] = []
|
|
1184
|
+
frameworks: set[str] = set()
|
|
1185
|
+
fixes: set[str] = set()
|
|
1186
|
+
for c in calls:
|
|
1187
|
+
pack = _match_framework_pack(c, language)
|
|
1188
|
+
if pack:
|
|
1189
|
+
frameworks.add(pack["framework"])
|
|
1190
|
+
if pack.get("fix"):
|
|
1191
|
+
fixes.add(pack["fix"])
|
|
1192
|
+
if pack.get("confidence") == "high":
|
|
1193
|
+
high_calls.append(c)
|
|
1194
|
+
else:
|
|
1195
|
+
medium_calls.append(c)
|
|
1196
|
+
continue
|
|
1197
|
+
|
|
1198
|
+
lower_c = c.lower()
|
|
1199
|
+
leaf = _call_leaf(c).lower()
|
|
1200
|
+
if lower_c in _HIGH_EXACT_LOWER:
|
|
1201
|
+
high_calls.append(c)
|
|
1202
|
+
continue
|
|
1203
|
+
if leaf in _HIGH_LEAF and _receiver_is_ioish(c):
|
|
1204
|
+
high_calls.append(c)
|
|
1205
|
+
continue
|
|
1206
|
+
# requests.<verb> style HTTP calls
|
|
1207
|
+
if leaf in {"get", "post", "put", "delete", "patch", "request"}:
|
|
1208
|
+
recv = _receiver_hint(c)
|
|
1209
|
+
if "requests" in recv or recv.endswith("http"):
|
|
1210
|
+
high_calls.append(c)
|
|
1211
|
+
continue
|
|
1212
|
+
if leaf in _MEDIUM_LEAF and _receiver_is_ioish(c):
|
|
1213
|
+
medium_calls.append(c)
|
|
1214
|
+
continue
|
|
1215
|
+
# Bare helper names without a receiver are ambiguous: if they
|
|
1216
|
+
# resolve to a local helper in the same file, treat as non-I/O.
|
|
1217
|
+
if "." not in c and leaf in _AMBIGUOUS_BARE:
|
|
1218
|
+
local_helper = conn.execute(
|
|
1219
|
+
"SELECT 1 FROM edges e "
|
|
1220
|
+
"JOIN symbols t ON e.target_id = t.id "
|
|
1221
|
+
"WHERE e.source_id = ? "
|
|
1222
|
+
"AND lower(t.name) = ? "
|
|
1223
|
+
"AND t.file_id = ? "
|
|
1224
|
+
"LIMIT 1",
|
|
1225
|
+
(r["id"], leaf, r["file_id"]),
|
|
1226
|
+
).fetchone()
|
|
1227
|
+
if local_helper:
|
|
1228
|
+
continue
|
|
1229
|
+
medium_calls.append(c)
|
|
1230
|
+
continue
|
|
1231
|
+
if leaf == "open":
|
|
1232
|
+
medium_calls.append(c)
|
|
1233
|
+
continue
|
|
1234
|
+
|
|
1235
|
+
if not high_calls and not medium_calls:
|
|
1236
|
+
continue
|
|
1237
|
+
|
|
1238
|
+
name_lower = (r["name"] or "").lower()
|
|
1239
|
+
if any(kw in name_lower for kw in _IO_WRAPPER_NAMES):
|
|
1240
|
+
continue
|
|
1241
|
+
|
|
1242
|
+
guard_applies = bool(frameworks and guard_hints)
|
|
1243
|
+
if high_calls:
|
|
1244
|
+
reason_calls = _dedupe(high_calls)[:2]
|
|
1245
|
+
reason_suffix = ""
|
|
1246
|
+
if frameworks:
|
|
1247
|
+
reason_suffix = f"; frameworks: {', '.join(sorted(frameworks))}"
|
|
1248
|
+
confidence = "high"
|
|
1249
|
+
if guard_applies:
|
|
1250
|
+
confidence = _lower_confidence(confidence)
|
|
1251
|
+
reason_suffix += f"; eager/batch guards: {', '.join(guard_hints[:2])}"
|
|
1252
|
+
results.append(
|
|
1253
|
+
_finding(
|
|
1254
|
+
"io-in-loop",
|
|
1255
|
+
"loop-query",
|
|
1256
|
+
r,
|
|
1257
|
+
f"I/O call ({', '.join(reason_calls)}) inside loop (N+1 pattern){reason_suffix}",
|
|
1258
|
+
confidence,
|
|
1259
|
+
evidence={
|
|
1260
|
+
"io_calls": _dedupe(high_calls + medium_calls)[:6],
|
|
1261
|
+
"frameworks": sorted(frameworks),
|
|
1262
|
+
"guard_hints": guard_hints,
|
|
1263
|
+
},
|
|
1264
|
+
fix="; ".join(sorted(fixes)) if fixes else None,
|
|
1265
|
+
)
|
|
1266
|
+
)
|
|
1267
|
+
else:
|
|
1268
|
+
reason_calls = _dedupe(medium_calls)[:2]
|
|
1269
|
+
reason_suffix = ""
|
|
1270
|
+
if frameworks:
|
|
1271
|
+
reason_suffix = f"; frameworks: {', '.join(sorted(frameworks))}"
|
|
1272
|
+
confidence = "medium"
|
|
1273
|
+
if guard_applies:
|
|
1274
|
+
confidence = _lower_confidence(confidence)
|
|
1275
|
+
reason_suffix += f"; eager/batch guards: {', '.join(guard_hints[:2])}"
|
|
1276
|
+
results.append(
|
|
1277
|
+
_finding(
|
|
1278
|
+
"io-in-loop",
|
|
1279
|
+
"loop-query",
|
|
1280
|
+
r,
|
|
1281
|
+
f"I/O-like call ({', '.join(reason_calls)}) inside loop (may be N+1){reason_suffix}",
|
|
1282
|
+
confidence,
|
|
1283
|
+
evidence={
|
|
1284
|
+
"io_calls": _dedupe(high_calls + medium_calls)[:6],
|
|
1285
|
+
"frameworks": sorted(frameworks),
|
|
1286
|
+
"guard_hints": guard_hints,
|
|
1287
|
+
},
|
|
1288
|
+
fix="; ".join(sorted(fixes)) if fixes else None,
|
|
1289
|
+
)
|
|
1290
|
+
)
|
|
1291
|
+
return results
|
|
1292
|
+
|
|
1293
|
+
|
|
1294
|
+
def detect_list_prepend(conn):
|
|
1295
|
+
"""insert(0, x), unshift(), or pop(0) inside a loop — O(n) per op
|
|
1296
|
+
due to array shifting, O(n^2) total."""
|
|
1297
|
+
try:
|
|
1298
|
+
rows = conn.execute(
|
|
1299
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
1300
|
+
"s.line_start, ms.front_ops_in_loop "
|
|
1301
|
+
"FROM symbols s "
|
|
1302
|
+
"JOIN files f ON s.file_id = f.id "
|
|
1303
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
1304
|
+
"WHERE s.kind IN ('function', 'method') "
|
|
1305
|
+
"AND ms.front_ops_in_loop = 1"
|
|
1306
|
+
).fetchall()
|
|
1307
|
+
except Exception:
|
|
1308
|
+
# Fallback for older indexes without front_ops_in_loop.
|
|
1309
|
+
rows = conn.execute(
|
|
1310
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
1311
|
+
"s.line_start, ms.calls_in_loops, '' as calls_in_loops_qualified "
|
|
1312
|
+
"FROM symbols s "
|
|
1313
|
+
"JOIN files f ON s.file_id = f.id "
|
|
1314
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
1315
|
+
"WHERE s.kind IN ('function', 'method') "
|
|
1316
|
+
"AND ms.loop_depth >= 1"
|
|
1317
|
+
).fetchall()
|
|
1318
|
+
|
|
1319
|
+
results = []
|
|
1320
|
+
for r in rows:
|
|
1321
|
+
if _is_test_path(r["file_path"]):
|
|
1322
|
+
continue
|
|
1323
|
+
# New indexes precompute the exact front-op signal.
|
|
1324
|
+
if _row_value(r, "front_ops_in_loop", None) == 1:
|
|
1325
|
+
results.append(
|
|
1326
|
+
_finding(
|
|
1327
|
+
"list-prepend",
|
|
1328
|
+
"insert-front",
|
|
1329
|
+
r,
|
|
1330
|
+
"Front insert/remove inside loop (O(n) shift per operation)",
|
|
1331
|
+
"high",
|
|
1332
|
+
)
|
|
1333
|
+
)
|
|
1334
|
+
continue
|
|
1335
|
+
# Fallback heuristic (conservative): only explicit front APIs.
|
|
1336
|
+
calls = _iter_loop_calls(r)
|
|
1337
|
+
if _call_in(calls, {"insert", "unshift", "shift", "appendleft", "popleft"}):
|
|
1338
|
+
results.append(
|
|
1339
|
+
_finding(
|
|
1340
|
+
"list-prepend",
|
|
1341
|
+
"insert-front",
|
|
1342
|
+
r,
|
|
1343
|
+
"Potential front insert/remove inside loop",
|
|
1344
|
+
"medium",
|
|
1345
|
+
)
|
|
1346
|
+
)
|
|
1347
|
+
return results
|
|
1348
|
+
|
|
1349
|
+
|
|
1350
|
+
def detect_sort_to_select(conn):
|
|
1351
|
+
"""Calling sort on a collection and then only using the first/last element.
|
|
1352
|
+
|
|
1353
|
+
O(n log n) sort when min()/max() is O(n), or heapq.nsmallest is O(n log k).
|
|
1354
|
+
Detection: function calls sort AND has subscript access, but does NOT
|
|
1355
|
+
iterate the full sorted result.
|
|
1356
|
+
"""
|
|
1357
|
+
rows = conn.execute(
|
|
1358
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
1359
|
+
"s.line_start, s.line_end "
|
|
1360
|
+
"FROM symbols s "
|
|
1361
|
+
"JOIN files f ON s.file_id = f.id "
|
|
1362
|
+
"WHERE s.kind IN ('function', 'method')"
|
|
1363
|
+
).fetchall()
|
|
1364
|
+
|
|
1365
|
+
sorted_index_re = re.compile(r"\bsorted\s*\([^)]*\)\s*\[\s*(?:-?\d+|:\s*[^]\n]+)\s*\]")
|
|
1366
|
+
inplace_sort_index_re = re.compile(
|
|
1367
|
+
r"\b([A-Za-z_][A-Za-z0-9_]*)\s*\.\s*sort\s*\([^)]*\).*?"
|
|
1368
|
+
r"\b\1\s*\[\s*(?:-?\d+|:\s*[^]\n]+)\s*\]",
|
|
1369
|
+
re.DOTALL,
|
|
1370
|
+
)
|
|
1371
|
+
generic_sort_index_re = re.compile(
|
|
1372
|
+
r"\bsort(?:ed)?\s*\([^)]*\).*?\[\s*(?:-?\d+|:\s*[^]\n]+)\s*\]",
|
|
1373
|
+
re.DOTALL,
|
|
1374
|
+
)
|
|
1375
|
+
|
|
1376
|
+
results = []
|
|
1377
|
+
for r in rows:
|
|
1378
|
+
if _is_test_path(r["file_path"]):
|
|
1379
|
+
continue
|
|
1380
|
+
snippet = _read_symbol_source(r["file_path"], r["line_start"], r["line_end"])
|
|
1381
|
+
if not snippet:
|
|
1382
|
+
continue
|
|
1383
|
+
|
|
1384
|
+
# Strong patterns: sorted(...)[0], sorted(... )[:k], arr.sort(); arr[0]
|
|
1385
|
+
if sorted_index_re.search(snippet) or inplace_sort_index_re.search(snippet):
|
|
1386
|
+
results.append(
|
|
1387
|
+
_finding(
|
|
1388
|
+
"sort-to-select",
|
|
1389
|
+
"full-sort",
|
|
1390
|
+
r,
|
|
1391
|
+
"Sort used only for first/last/top-k selection",
|
|
1392
|
+
"high",
|
|
1393
|
+
)
|
|
1394
|
+
)
|
|
1395
|
+
continue
|
|
1396
|
+
|
|
1397
|
+
# Fallback pattern for other languages (sort(...) then index/slice).
|
|
1398
|
+
if generic_sort_index_re.search(snippet):
|
|
1399
|
+
results.append(
|
|
1400
|
+
_finding(
|
|
1401
|
+
"sort-to-select",
|
|
1402
|
+
"full-sort",
|
|
1403
|
+
r,
|
|
1404
|
+
"Potential full sort followed by index/slice selection",
|
|
1405
|
+
"medium",
|
|
1406
|
+
)
|
|
1407
|
+
)
|
|
1408
|
+
return results
|
|
1409
|
+
|
|
1410
|
+
|
|
1411
|
+
def detect_loop_lookup(conn):
|
|
1412
|
+
""".index(), .indexOf(), .contains(), .includes() called inside a loop.
|
|
1413
|
+
|
|
1414
|
+
Each call is O(m) linear scan on the lookup collection, total O(n*m).
|
|
1415
|
+
Pre-building a set gives O(1) per lookup, O(n+m) total.
|
|
1416
|
+
"""
|
|
1417
|
+
try:
|
|
1418
|
+
rows = conn.execute(
|
|
1419
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
1420
|
+
"s.line_start, ms.loop_lookup_calls, ms.calls_in_loops, "
|
|
1421
|
+
"ms.calls_in_loops_qualified "
|
|
1422
|
+
"FROM symbols s "
|
|
1423
|
+
"JOIN files f ON s.file_id = f.id "
|
|
1424
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
1425
|
+
"WHERE s.kind IN ('function', 'method') "
|
|
1426
|
+
"AND ms.loop_depth >= 1"
|
|
1427
|
+
).fetchall()
|
|
1428
|
+
except Exception:
|
|
1429
|
+
rows = conn.execute(
|
|
1430
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
1431
|
+
"s.line_start, '' as loop_lookup_calls, ms.calls_in_loops, "
|
|
1432
|
+
"'' as calls_in_loops_qualified "
|
|
1433
|
+
"FROM symbols s "
|
|
1434
|
+
"JOIN files f ON s.file_id = f.id "
|
|
1435
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
1436
|
+
"WHERE s.kind IN ('function', 'method') "
|
|
1437
|
+
"AND ms.loop_depth >= 1"
|
|
1438
|
+
).fetchall()
|
|
1439
|
+
|
|
1440
|
+
_LOOKUP_CALLS = {
|
|
1441
|
+
"index",
|
|
1442
|
+
"indexOf",
|
|
1443
|
+
"lastIndexOf",
|
|
1444
|
+
"contains",
|
|
1445
|
+
"includes",
|
|
1446
|
+
"Contains",
|
|
1447
|
+
"IndexOf",
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
results = []
|
|
1451
|
+
for r in rows:
|
|
1452
|
+
if _is_test_path(r["file_path"]):
|
|
1453
|
+
continue
|
|
1454
|
+
lookup_calls = _json_list(_row_value(r, "loop_lookup_calls", ""))
|
|
1455
|
+
if lookup_calls:
|
|
1456
|
+
results.append(
|
|
1457
|
+
_finding(
|
|
1458
|
+
"loop-lookup",
|
|
1459
|
+
"method-scan",
|
|
1460
|
+
r,
|
|
1461
|
+
f"Linear lookup ({', '.join(lookup_calls[:2])}) called on invariant collection",
|
|
1462
|
+
"high",
|
|
1463
|
+
)
|
|
1464
|
+
)
|
|
1465
|
+
continue
|
|
1466
|
+
# Fallback for older indexes: conservative matching only.
|
|
1467
|
+
calls = _iter_loop_calls(r)
|
|
1468
|
+
fallback_hits = _call_in(calls, _LOOKUP_CALLS)
|
|
1469
|
+
if fallback_hits:
|
|
1470
|
+
results.append(
|
|
1471
|
+
_finding(
|
|
1472
|
+
"loop-lookup",
|
|
1473
|
+
"method-scan",
|
|
1474
|
+
r,
|
|
1475
|
+
f"Linear lookup ({', '.join(fallback_hits[:2])}) called inside loop",
|
|
1476
|
+
"low",
|
|
1477
|
+
)
|
|
1478
|
+
)
|
|
1479
|
+
return results
|
|
1480
|
+
|
|
1481
|
+
|
|
1482
|
+
# ---------------------------------------------------------------------------
|
|
1483
|
+
# Tier 2 detectors: enhanced signals
|
|
1484
|
+
# ---------------------------------------------------------------------------
|
|
1485
|
+
|
|
1486
|
+
|
|
1487
|
+
def detect_branching_recursion(conn):
|
|
1488
|
+
"""Functions with 2+ self-call sites and no memoization.
|
|
1489
|
+
|
|
1490
|
+
Generalizes fibonacci to any branching recursion: tree traversals,
|
|
1491
|
+
divide-and-conquer, DP problems. O(2^n) -> O(n) with memoization.
|
|
1492
|
+
"""
|
|
1493
|
+
# self_call_count column may not exist in older DBs — fall back safely
|
|
1494
|
+
try:
|
|
1495
|
+
rows = conn.execute(
|
|
1496
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
1497
|
+
"s.line_start, ms.self_call_count "
|
|
1498
|
+
"FROM symbols s "
|
|
1499
|
+
"JOIN files f ON s.file_id = f.id "
|
|
1500
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
1501
|
+
"WHERE s.kind IN ('function', 'method') "
|
|
1502
|
+
"AND ms.self_call_count >= 2"
|
|
1503
|
+
).fetchall()
|
|
1504
|
+
except Exception:
|
|
1505
|
+
return []
|
|
1506
|
+
|
|
1507
|
+
results = []
|
|
1508
|
+
for r in rows:
|
|
1509
|
+
if _is_test_path(r["file_path"]):
|
|
1510
|
+
continue
|
|
1511
|
+
# Skip fibonacci — already covered by detect_naive_fibonacci
|
|
1512
|
+
name_lower = (r["name"] or "").lower()
|
|
1513
|
+
if "fib" in name_lower:
|
|
1514
|
+
continue
|
|
1515
|
+
# Skip tree/AST walkers — recursive traversal of children is
|
|
1516
|
+
# intentional and doesn't have overlapping subproblems
|
|
1517
|
+
_WALKER_NAMES = {
|
|
1518
|
+
"walk",
|
|
1519
|
+
"visit",
|
|
1520
|
+
"traverse",
|
|
1521
|
+
"search",
|
|
1522
|
+
"scan",
|
|
1523
|
+
"crawl",
|
|
1524
|
+
"descend",
|
|
1525
|
+
"recurse",
|
|
1526
|
+
"dfs",
|
|
1527
|
+
"bfs",
|
|
1528
|
+
}
|
|
1529
|
+
if any(kw in name_lower for kw in _WALKER_NAMES):
|
|
1530
|
+
continue
|
|
1531
|
+
# Check for memoization edge
|
|
1532
|
+
memo_edge = conn.execute(
|
|
1533
|
+
"SELECT 1 FROM edges e "
|
|
1534
|
+
"JOIN symbols t ON e.target_id = t.id "
|
|
1535
|
+
"WHERE e.source_id = ? "
|
|
1536
|
+
"AND t.name IN ('lru_cache', 'cache', 'memoize', 'memo', "
|
|
1537
|
+
" 'functools.lru_cache', 'functools.cache') "
|
|
1538
|
+
"LIMIT 1",
|
|
1539
|
+
(r["id"],),
|
|
1540
|
+
).fetchone()
|
|
1541
|
+
if memo_edge:
|
|
1542
|
+
continue
|
|
1543
|
+
results.append(
|
|
1544
|
+
_finding(
|
|
1545
|
+
"branching-recursion",
|
|
1546
|
+
"naive-branching",
|
|
1547
|
+
r,
|
|
1548
|
+
f"Branching recursion ({r['self_call_count']} self-calls) without memoization",
|
|
1549
|
+
"high",
|
|
1550
|
+
)
|
|
1551
|
+
)
|
|
1552
|
+
return results
|
|
1553
|
+
|
|
1554
|
+
|
|
1555
|
+
def detect_quadratic_string(conn):
|
|
1556
|
+
"""String concatenation via += inside a loop — O(n^2) due to
|
|
1557
|
+
immutable string reallocation in Python/Java/Go.
|
|
1558
|
+
"""
|
|
1559
|
+
try:
|
|
1560
|
+
rows = conn.execute(
|
|
1561
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
1562
|
+
"s.line_start, ms.str_concat_in_loop "
|
|
1563
|
+
"FROM symbols s "
|
|
1564
|
+
"JOIN files f ON s.file_id = f.id "
|
|
1565
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
1566
|
+
"WHERE s.kind IN ('function', 'method') "
|
|
1567
|
+
"AND ms.str_concat_in_loop = 1"
|
|
1568
|
+
).fetchall()
|
|
1569
|
+
except Exception:
|
|
1570
|
+
return []
|
|
1571
|
+
|
|
1572
|
+
results = []
|
|
1573
|
+
for r in rows:
|
|
1574
|
+
if _is_test_path(r["file_path"]):
|
|
1575
|
+
continue
|
|
1576
|
+
results.append(
|
|
1577
|
+
_finding(
|
|
1578
|
+
"quadratic-string",
|
|
1579
|
+
"augment-concat",
|
|
1580
|
+
r,
|
|
1581
|
+
"String += in loop (O(n^2) due to immutable reallocation)",
|
|
1582
|
+
"high",
|
|
1583
|
+
)
|
|
1584
|
+
)
|
|
1585
|
+
return results
|
|
1586
|
+
|
|
1587
|
+
|
|
1588
|
+
def detect_loop_invariant_call(conn):
|
|
1589
|
+
"""Calls inside loops whose arguments don't reference the loop variable.
|
|
1590
|
+
|
|
1591
|
+
These can be hoisted before the loop to avoid repeated computation.
|
|
1592
|
+
Suppresses common intentional per-iteration calls (logging, metrics, etc.).
|
|
1593
|
+
"""
|
|
1594
|
+
try:
|
|
1595
|
+
rows = conn.execute(
|
|
1596
|
+
"SELECT s.id, s.name, s.qualified_name, s.kind, f.path as file_path, "
|
|
1597
|
+
"s.line_start, ms.loop_invariant_calls "
|
|
1598
|
+
"FROM symbols s "
|
|
1599
|
+
"JOIN files f ON s.file_id = f.id "
|
|
1600
|
+
"JOIN math_signals ms ON ms.symbol_id = s.id "
|
|
1601
|
+
"WHERE s.kind IN ('function', 'method') "
|
|
1602
|
+
"AND ms.loop_invariant_calls IS NOT NULL "
|
|
1603
|
+
"AND ms.loop_invariant_calls != '[]'"
|
|
1604
|
+
).fetchall()
|
|
1605
|
+
except Exception:
|
|
1606
|
+
return []
|
|
1607
|
+
|
|
1608
|
+
# Calls that are intentionally per-iteration (suppress)
|
|
1609
|
+
_INTENTIONAL_CALLS = {
|
|
1610
|
+
# Logging / output
|
|
1611
|
+
"print",
|
|
1612
|
+
"log",
|
|
1613
|
+
"debug",
|
|
1614
|
+
"info",
|
|
1615
|
+
"warn",
|
|
1616
|
+
"warning",
|
|
1617
|
+
"error",
|
|
1618
|
+
# Collection mutation
|
|
1619
|
+
"append",
|
|
1620
|
+
"add",
|
|
1621
|
+
"push",
|
|
1622
|
+
"extend",
|
|
1623
|
+
"write",
|
|
1624
|
+
"send",
|
|
1625
|
+
"get",
|
|
1626
|
+
"values",
|
|
1627
|
+
"items",
|
|
1628
|
+
"keys",
|
|
1629
|
+
"update",
|
|
1630
|
+
"pop",
|
|
1631
|
+
"remove",
|
|
1632
|
+
"insert",
|
|
1633
|
+
"setdefault",
|
|
1634
|
+
"discard",
|
|
1635
|
+
# String methods (inherently per-item)
|
|
1636
|
+
"startswith",
|
|
1637
|
+
"endswith",
|
|
1638
|
+
"replace",
|
|
1639
|
+
"format",
|
|
1640
|
+
"strip",
|
|
1641
|
+
"split",
|
|
1642
|
+
"join",
|
|
1643
|
+
"lower",
|
|
1644
|
+
"upper",
|
|
1645
|
+
"lstrip",
|
|
1646
|
+
"rstrip",
|
|
1647
|
+
"encode",
|
|
1648
|
+
"decode",
|
|
1649
|
+
"ljust",
|
|
1650
|
+
"rjust",
|
|
1651
|
+
"center",
|
|
1652
|
+
"zfill",
|
|
1653
|
+
# Event / tracking
|
|
1654
|
+
"emit",
|
|
1655
|
+
"track",
|
|
1656
|
+
"record",
|
|
1657
|
+
"increment",
|
|
1658
|
+
"decrement",
|
|
1659
|
+
# Iteration helpers / builtins
|
|
1660
|
+
"enumerate",
|
|
1661
|
+
"zip",
|
|
1662
|
+
"range",
|
|
1663
|
+
"sorted",
|
|
1664
|
+
"reversed",
|
|
1665
|
+
"list",
|
|
1666
|
+
"dict",
|
|
1667
|
+
"set",
|
|
1668
|
+
"tuple",
|
|
1669
|
+
"len",
|
|
1670
|
+
"str",
|
|
1671
|
+
"int",
|
|
1672
|
+
"float",
|
|
1673
|
+
"bool",
|
|
1674
|
+
"bytes",
|
|
1675
|
+
"type",
|
|
1676
|
+
# Math / comparison builtins (per-item reductions)
|
|
1677
|
+
"max",
|
|
1678
|
+
"min",
|
|
1679
|
+
"sum",
|
|
1680
|
+
"abs",
|
|
1681
|
+
"round",
|
|
1682
|
+
"pow",
|
|
1683
|
+
"isinstance",
|
|
1684
|
+
"issubclass",
|
|
1685
|
+
"hasattr",
|
|
1686
|
+
"getattr",
|
|
1687
|
+
"setattr",
|
|
1688
|
+
# File / IO
|
|
1689
|
+
"resolve",
|
|
1690
|
+
"execute",
|
|
1691
|
+
"fetchone",
|
|
1692
|
+
"fetchall",
|
|
1693
|
+
"read_text",
|
|
1694
|
+
"read_bytes",
|
|
1695
|
+
"open",
|
|
1696
|
+
# Control flow
|
|
1697
|
+
"sleep",
|
|
1698
|
+
"yield",
|
|
1699
|
+
}
|
|
1700
|
+
|
|
1701
|
+
results = []
|
|
1702
|
+
for r in rows:
|
|
1703
|
+
if _is_test_path(r["file_path"]):
|
|
1704
|
+
continue
|
|
1705
|
+
inv_calls = json.loads(r["loop_invariant_calls"]) if r["loop_invariant_calls"] else []
|
|
1706
|
+
# Filter out intentional per-iteration calls
|
|
1707
|
+
flagged = [c for c in inv_calls if c.lower() not in _INTENTIONAL_CALLS]
|
|
1708
|
+
if not flagged:
|
|
1709
|
+
continue
|
|
1710
|
+
results.append(
|
|
1711
|
+
_finding(
|
|
1712
|
+
"loop-invariant-call",
|
|
1713
|
+
"repeated-call",
|
|
1714
|
+
r,
|
|
1715
|
+
f"Loop-invariant call ({', '.join(flagged[:3])}) can be hoisted before loop",
|
|
1716
|
+
"medium",
|
|
1717
|
+
)
|
|
1718
|
+
)
|
|
1719
|
+
return results
|
|
1720
|
+
|
|
1721
|
+
|
|
1722
|
+
# ---------------------------------------------------------------------------
|
|
1723
|
+
# Confidence calibration
|
|
1724
|
+
# ---------------------------------------------------------------------------
|
|
1725
|
+
|
|
1726
|
+
_CONFIDENCE_ORDER = ["low", "medium", "high"]
|
|
1727
|
+
|
|
1728
|
+
_DETECTOR_METADATA = {
|
|
1729
|
+
"sorting": {"precision": "high", "impact": "medium", "tags": ["ordering", "nested-loop"]},
|
|
1730
|
+
"search-sorted": {"precision": "low", "impact": "medium", "tags": ["search", "sorted-data"]},
|
|
1731
|
+
"membership": {"precision": "medium", "impact": "high", "tags": ["collections", "n2"]},
|
|
1732
|
+
"string-concat": {"precision": "medium", "impact": "medium", "tags": ["string", "quadratic"]},
|
|
1733
|
+
"unique": {"precision": "medium", "impact": "high", "tags": ["dedup", "n2"]},
|
|
1734
|
+
"max-min": {"precision": "medium", "impact": "low", "tags": ["idiom"]},
|
|
1735
|
+
"accumulation": {"precision": "medium", "impact": "low", "tags": ["idiom"]},
|
|
1736
|
+
"manual-power": {"precision": "high", "impact": "medium", "tags": ["math"]},
|
|
1737
|
+
"manual-gcd": {"precision": "high", "impact": "low", "tags": ["math"]},
|
|
1738
|
+
"fibonacci": {"precision": "high", "impact": "high", "tags": ["recursion", "exponential"]},
|
|
1739
|
+
"nested-lookup": {"precision": "medium", "impact": "high", "tags": ["join", "nxm"]},
|
|
1740
|
+
"groupby": {"precision": "medium", "impact": "low", "tags": ["idiom"]},
|
|
1741
|
+
"string-reverse": {"precision": "low", "impact": "low", "tags": ["idiom"]},
|
|
1742
|
+
"matrix-mult": {"precision": "high", "impact": "high", "tags": ["math", "triple-loop"]},
|
|
1743
|
+
"busy-wait": {"precision": "high", "impact": "high", "tags": ["concurrency"]},
|
|
1744
|
+
"regex-in-loop": {"precision": "high", "impact": "high", "tags": ["string", "regex"]},
|
|
1745
|
+
"io-in-loop": {"precision": "high", "impact": "high", "tags": ["io", "n+1"]},
|
|
1746
|
+
"list-prepend": {"precision": "high", "impact": "high", "tags": ["collections", "front-shift"]},
|
|
1747
|
+
"sort-to-select": {"precision": "high", "impact": "medium", "tags": ["ordering"]},
|
|
1748
|
+
"loop-lookup": {"precision": "high", "impact": "high", "tags": ["collections", "lookup"]},
|
|
1749
|
+
"branching-recursion": {"precision": "high", "impact": "high", "tags": ["recursion", "dp"]},
|
|
1750
|
+
"quadratic-string": {"precision": "high", "impact": "high", "tags": ["string", "quadratic"]},
|
|
1751
|
+
"loop-invariant-call": {"precision": "medium", "impact": "medium", "tags": ["hoisting"]},
|
|
1752
|
+
}
|
|
1753
|
+
|
|
1754
|
+
|
|
1755
|
+
def _detector_meta(task_id: str) -> dict:
|
|
1756
|
+
return _DETECTOR_METADATA.get(
|
|
1757
|
+
task_id,
|
|
1758
|
+
{"precision": "medium", "impact": "medium", "tags": []},
|
|
1759
|
+
)
|
|
1760
|
+
|
|
1761
|
+
|
|
1762
|
+
def _boost_confidence(confidence: str) -> str:
|
|
1763
|
+
"""Raise confidence by one level."""
|
|
1764
|
+
idx = _CONFIDENCE_ORDER.index(confidence) if confidence in _CONFIDENCE_ORDER else 1
|
|
1765
|
+
return _CONFIDENCE_ORDER[min(idx + 1, len(_CONFIDENCE_ORDER) - 1)]
|
|
1766
|
+
|
|
1767
|
+
|
|
1768
|
+
def _lower_confidence(confidence: str) -> str:
|
|
1769
|
+
"""Lower confidence by one level."""
|
|
1770
|
+
idx = _CONFIDENCE_ORDER.index(confidence) if confidence in _CONFIDENCE_ORDER else 1
|
|
1771
|
+
return _CONFIDENCE_ORDER[max(idx - 1, 0)]
|
|
1772
|
+
|
|
1773
|
+
|
|
1774
|
+
_SIGNAL_COLUMNS = [
|
|
1775
|
+
("has_nested_loops", "nested_loops"),
|
|
1776
|
+
("subscript_in_loops", "subscript_in_loops"),
|
|
1777
|
+
("loop_with_compare", "loop_compare"),
|
|
1778
|
+
("loop_with_accumulator", "loop_accumulator"),
|
|
1779
|
+
("loop_with_multiplication", "loop_multiplication"),
|
|
1780
|
+
("loop_with_modulo", "loop_modulo"),
|
|
1781
|
+
("str_concat_in_loop", "string_concat"),
|
|
1782
|
+
("front_ops_in_loop", "front_ops"),
|
|
1783
|
+
]
|
|
1784
|
+
|
|
1785
|
+
_PROFILE_BALANCED = "balanced"
|
|
1786
|
+
_PROFILE_STRICT = "strict"
|
|
1787
|
+
_PROFILE_AGGRESSIVE = "aggressive"
|
|
1788
|
+
_VALID_PROFILES = {
|
|
1789
|
+
_PROFILE_BALANCED,
|
|
1790
|
+
_PROFILE_STRICT,
|
|
1791
|
+
_PROFILE_AGGRESSIVE,
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1794
|
+
|
|
1795
|
+
def _chunked(values: list[int], size: int = 500):
|
|
1796
|
+
for i in range(0, len(values), size):
|
|
1797
|
+
yield values[i : i + size]
|
|
1798
|
+
|
|
1799
|
+
|
|
1800
|
+
def _symbol_context(conn, symbol_ids: list[int]) -> dict[int, dict]:
|
|
1801
|
+
"""Load calibration + evidence context for findings in bulk."""
|
|
1802
|
+
context: dict[int, dict] = {
|
|
1803
|
+
sid: {
|
|
1804
|
+
"signals": [],
|
|
1805
|
+
"loop_depth": 0,
|
|
1806
|
+
"loop_bound_small": 0,
|
|
1807
|
+
"caller_count": 0,
|
|
1808
|
+
"runtime_call_count": 0,
|
|
1809
|
+
"runtime_p99_latency_ms": None,
|
|
1810
|
+
"runtime_error_rate": 0.0,
|
|
1811
|
+
"runtime_otel_db_system": None,
|
|
1812
|
+
"runtime_otel_db_operation": None,
|
|
1813
|
+
"runtime_otel_db_statement_type": None,
|
|
1814
|
+
}
|
|
1815
|
+
for sid in symbol_ids
|
|
1816
|
+
}
|
|
1817
|
+
if not symbol_ids:
|
|
1818
|
+
return context
|
|
1819
|
+
|
|
1820
|
+
# Static AST signals
|
|
1821
|
+
for chunk in _chunked(symbol_ids):
|
|
1822
|
+
ph = ",".join("?" for _ in chunk)
|
|
1823
|
+
rows = conn.execute(
|
|
1824
|
+
f"SELECT symbol_id, loop_depth, loop_bound_small, "
|
|
1825
|
+
f"has_nested_loops, subscript_in_loops, loop_with_compare, "
|
|
1826
|
+
f"loop_with_accumulator, loop_with_multiplication, loop_with_modulo, "
|
|
1827
|
+
f"str_concat_in_loop, front_ops_in_loop "
|
|
1828
|
+
f"FROM math_signals WHERE symbol_id IN ({ph})",
|
|
1829
|
+
chunk,
|
|
1830
|
+
).fetchall()
|
|
1831
|
+
for r in rows:
|
|
1832
|
+
sid = r["symbol_id"]
|
|
1833
|
+
if sid not in context:
|
|
1834
|
+
continue
|
|
1835
|
+
ctx = context[sid]
|
|
1836
|
+
ctx["loop_depth"] = int(r["loop_depth"] or 0)
|
|
1837
|
+
ctx["loop_bound_small"] = int(r["loop_bound_small"] or 0)
|
|
1838
|
+
signals: list[str] = []
|
|
1839
|
+
for col, label in _SIGNAL_COLUMNS:
|
|
1840
|
+
if r[col]:
|
|
1841
|
+
signals.append(label)
|
|
1842
|
+
ctx["signals"] = signals
|
|
1843
|
+
|
|
1844
|
+
# Caller counts
|
|
1845
|
+
for chunk in _chunked(symbol_ids):
|
|
1846
|
+
ph = ",".join("?" for _ in chunk)
|
|
1847
|
+
rows = conn.execute(
|
|
1848
|
+
f"SELECT target_id, COUNT(*) AS cnt "
|
|
1849
|
+
f"FROM edges WHERE kind = 'call' AND target_id IN ({ph}) "
|
|
1850
|
+
f"GROUP BY target_id",
|
|
1851
|
+
chunk,
|
|
1852
|
+
).fetchall()
|
|
1853
|
+
for r in rows:
|
|
1854
|
+
sid = r["target_id"]
|
|
1855
|
+
if sid in context:
|
|
1856
|
+
context[sid]["caller_count"] = int(r["cnt"] or 0)
|
|
1857
|
+
|
|
1858
|
+
# Runtime traces (optional table for legacy DB compatibility)
|
|
1859
|
+
try:
|
|
1860
|
+
for chunk in _chunked(symbol_ids):
|
|
1861
|
+
ph = ",".join("?" for _ in chunk)
|
|
1862
|
+
rows = conn.execute(
|
|
1863
|
+
f"SELECT symbol_id, SUM(call_count) AS total_calls, "
|
|
1864
|
+
f"MAX(p99_latency_ms) AS p99_ms, MAX(error_rate) AS max_err, "
|
|
1865
|
+
f"MAX(otel_db_system) AS db_system, "
|
|
1866
|
+
f"MAX(otel_db_operation) AS db_operation, "
|
|
1867
|
+
f"MAX(otel_db_statement_type) AS db_statement_type "
|
|
1868
|
+
f"FROM runtime_stats "
|
|
1869
|
+
f"WHERE symbol_id IN ({ph}) "
|
|
1870
|
+
f"GROUP BY symbol_id",
|
|
1871
|
+
chunk,
|
|
1872
|
+
).fetchall()
|
|
1873
|
+
for r in rows:
|
|
1874
|
+
sid = r["symbol_id"]
|
|
1875
|
+
if sid not in context:
|
|
1876
|
+
continue
|
|
1877
|
+
context[sid]["runtime_call_count"] = int(r["total_calls"] or 0)
|
|
1878
|
+
context[sid]["runtime_p99_latency_ms"] = r["p99_ms"]
|
|
1879
|
+
context[sid]["runtime_error_rate"] = float(r["max_err"] or 0.0)
|
|
1880
|
+
context[sid]["runtime_otel_db_system"] = r["db_system"]
|
|
1881
|
+
context[sid]["runtime_otel_db_operation"] = r["db_operation"]
|
|
1882
|
+
context[sid]["runtime_otel_db_statement_type"] = r["db_statement_type"]
|
|
1883
|
+
except Exception:
|
|
1884
|
+
pass
|
|
1885
|
+
|
|
1886
|
+
return context
|
|
1887
|
+
|
|
1888
|
+
|
|
1889
|
+
def _merge_evidence(existing: dict | None, enriched: dict) -> dict:
|
|
1890
|
+
if not existing:
|
|
1891
|
+
return enriched
|
|
1892
|
+
merged = dict(existing)
|
|
1893
|
+
for k, v in enriched.items():
|
|
1894
|
+
if k not in merged:
|
|
1895
|
+
merged[k] = v
|
|
1896
|
+
continue
|
|
1897
|
+
current = merged[k]
|
|
1898
|
+
if isinstance(current, list) and isinstance(v, list):
|
|
1899
|
+
merged[k] = _dedupe([*current, *v])
|
|
1900
|
+
elif isinstance(current, dict) and isinstance(v, dict):
|
|
1901
|
+
tmp = dict(current)
|
|
1902
|
+
tmp.update(v)
|
|
1903
|
+
merged[k] = tmp
|
|
1904
|
+
else:
|
|
1905
|
+
merged[k] = v
|
|
1906
|
+
return merged
|
|
1907
|
+
|
|
1908
|
+
|
|
1909
|
+
def _build_evidence(context: dict) -> dict:
|
|
1910
|
+
evidence = {
|
|
1911
|
+
"signal_count": len(context.get("signals", [])),
|
|
1912
|
+
"signals": context.get("signals", []),
|
|
1913
|
+
"loop_depth": int(context.get("loop_depth", 0) or 0),
|
|
1914
|
+
"loop_bound_small": bool(context.get("loop_bound_small", 0)),
|
|
1915
|
+
"caller_count": int(context.get("caller_count", 0) or 0),
|
|
1916
|
+
}
|
|
1917
|
+
runtime_calls = int(context.get("runtime_call_count", 0) or 0)
|
|
1918
|
+
runtime_p99 = context.get("runtime_p99_latency_ms")
|
|
1919
|
+
runtime_error = float(context.get("runtime_error_rate", 0.0) or 0.0)
|
|
1920
|
+
runtime_db_system = context.get("runtime_otel_db_system")
|
|
1921
|
+
runtime_db_operation = context.get("runtime_otel_db_operation")
|
|
1922
|
+
runtime_db_statement_type = context.get("runtime_otel_db_statement_type")
|
|
1923
|
+
if runtime_calls > 0 or runtime_p99 is not None:
|
|
1924
|
+
evidence["runtime"] = {
|
|
1925
|
+
"call_count": runtime_calls,
|
|
1926
|
+
"p99_latency_ms": runtime_p99,
|
|
1927
|
+
"error_rate": runtime_error,
|
|
1928
|
+
"db_system": runtime_db_system,
|
|
1929
|
+
"db_operation": runtime_db_operation,
|
|
1930
|
+
"db_statement_type": runtime_db_statement_type,
|
|
1931
|
+
}
|
|
1932
|
+
return evidence
|
|
1933
|
+
|
|
1934
|
+
|
|
1935
|
+
def _build_evidence_path(finding: dict, context: dict) -> list[str]:
|
|
1936
|
+
path = [f"Observed pattern: {finding['reason']}"]
|
|
1937
|
+
signals = context.get("signals", [])
|
|
1938
|
+
if signals:
|
|
1939
|
+
path.append(f"Static evidence: {', '.join(signals[:4])}")
|
|
1940
|
+
runtime_calls = int(context.get("runtime_call_count", 0) or 0)
|
|
1941
|
+
runtime_p99 = context.get("runtime_p99_latency_ms")
|
|
1942
|
+
runtime_db_system = context.get("runtime_otel_db_system")
|
|
1943
|
+
runtime_db_operation = context.get("runtime_otel_db_operation") or context.get("runtime_otel_db_statement_type")
|
|
1944
|
+
if runtime_calls > 0:
|
|
1945
|
+
if runtime_p99 is not None:
|
|
1946
|
+
path.append(f"Runtime impact: {runtime_calls} calls, p99 {runtime_p99:.0f}ms")
|
|
1947
|
+
else:
|
|
1948
|
+
path.append(f"Runtime impact: {runtime_calls} calls")
|
|
1949
|
+
if runtime_db_system or runtime_db_operation:
|
|
1950
|
+
path.append(
|
|
1951
|
+
"Runtime semantics: db_system={} db_operation={}".format(
|
|
1952
|
+
runtime_db_system or "n/a",
|
|
1953
|
+
runtime_db_operation or "n/a",
|
|
1954
|
+
)
|
|
1955
|
+
)
|
|
1956
|
+
path.append(f"Recommendation: replace `{finding['detected_way']}` with `{finding['suggested_way']}`.")
|
|
1957
|
+
return path
|
|
1958
|
+
|
|
1959
|
+
|
|
1960
|
+
def _impact_score(finding: dict, context: dict) -> float:
|
|
1961
|
+
"""Rank finding urgency using static + runtime evidence."""
|
|
1962
|
+
confidence_base = {"high": 60.0, "medium": 35.0, "low": 15.0}
|
|
1963
|
+
impact_weight = {"high": 12.0, "medium": 6.0, "low": 2.0}
|
|
1964
|
+
|
|
1965
|
+
score = confidence_base.get(finding.get("confidence", "medium"), 30.0)
|
|
1966
|
+
score += impact_weight.get(finding.get("impact", "medium"), 5.0)
|
|
1967
|
+
|
|
1968
|
+
loop_depth = int(context.get("loop_depth", 0) or 0)
|
|
1969
|
+
score += min(12.0, loop_depth * 2.0)
|
|
1970
|
+
|
|
1971
|
+
caller_count = int(context.get("caller_count", 0) or 0)
|
|
1972
|
+
score += min(10.0, caller_count * 1.5)
|
|
1973
|
+
|
|
1974
|
+
runtime_calls = int(context.get("runtime_call_count", 0) or 0)
|
|
1975
|
+
runtime_p99 = context.get("runtime_p99_latency_ms")
|
|
1976
|
+
runtime_error = float(context.get("runtime_error_rate", 0.0) or 0.0)
|
|
1977
|
+
runtime_db_system = context.get("runtime_otel_db_system")
|
|
1978
|
+
runtime_db_operation = (
|
|
1979
|
+
context.get("runtime_otel_db_operation") or context.get("runtime_otel_db_statement_type") or ""
|
|
1980
|
+
)
|
|
1981
|
+
runtime_db_operation = str(runtime_db_operation).upper()
|
|
1982
|
+
runtime_multiplier = 0.65
|
|
1983
|
+
if runtime_db_system:
|
|
1984
|
+
runtime_multiplier = 1.0
|
|
1985
|
+
if runtime_db_operation in {"INSERT", "UPDATE", "DELETE", "UPSERT", "MERGE", "REPLACE"}:
|
|
1986
|
+
runtime_multiplier = 1.25
|
|
1987
|
+
elif runtime_db_operation in {"SELECT", "READ", "QUERY", "GET"}:
|
|
1988
|
+
runtime_multiplier = 1.0
|
|
1989
|
+
else:
|
|
1990
|
+
runtime_multiplier = 0.9
|
|
1991
|
+
if runtime_calls:
|
|
1992
|
+
score += min(20.0, (len(str(max(1, runtime_calls))) - 1) * 5.0) * runtime_multiplier
|
|
1993
|
+
if runtime_p99 is not None:
|
|
1994
|
+
latency_mult = 1.1 if runtime_db_system else 0.9
|
|
1995
|
+
score += min(15.0, float(runtime_p99) / 40.0) * latency_mult
|
|
1996
|
+
if runtime_error > 0:
|
|
1997
|
+
score += min(8.0, runtime_error * 100.0)
|
|
1998
|
+
if runtime_db_system:
|
|
1999
|
+
score += 2.5
|
|
2000
|
+
if runtime_db_operation in {"INSERT", "UPDATE", "DELETE", "UPSERT", "MERGE", "REPLACE"}:
|
|
2001
|
+
score += 3.5
|
|
2002
|
+
|
|
2003
|
+
if context.get("loop_bound_small", 0):
|
|
2004
|
+
score -= 8.0
|
|
2005
|
+
|
|
2006
|
+
return round(max(0.0, score), 2)
|
|
2007
|
+
|
|
2008
|
+
|
|
2009
|
+
def _impact_band(score: float) -> str:
|
|
2010
|
+
if score >= 80:
|
|
2011
|
+
return "high"
|
|
2012
|
+
if score >= 45:
|
|
2013
|
+
return "medium"
|
|
2014
|
+
return "low"
|
|
2015
|
+
|
|
2016
|
+
|
|
2017
|
+
def _calibrate_finding(finding: dict, context: dict | None) -> dict:
|
|
2018
|
+
"""Adjust confidence using static and runtime context."""
|
|
2019
|
+
ctx = context or {}
|
|
2020
|
+
caller_count = int(ctx.get("caller_count", 0) or 0)
|
|
2021
|
+
loop_bound_small = bool(ctx.get("loop_bound_small", 0))
|
|
2022
|
+
runtime_calls = int(ctx.get("runtime_call_count", 0) or 0)
|
|
2023
|
+
runtime_p99 = ctx.get("runtime_p99_latency_ms")
|
|
2024
|
+
runtime_error = float(ctx.get("runtime_error_rate", 0.0) or 0.0)
|
|
2025
|
+
runtime_db_system = ctx.get("runtime_otel_db_system")
|
|
2026
|
+
runtime_db_operation = ctx.get("runtime_otel_db_operation") or ctx.get("runtime_otel_db_statement_type") or ""
|
|
2027
|
+
runtime_db_operation = str(runtime_db_operation).upper()
|
|
2028
|
+
|
|
2029
|
+
if caller_count >= 5:
|
|
2030
|
+
finding["confidence"] = _boost_confidence(finding["confidence"])
|
|
2031
|
+
finding["reason"] += f" (hot: {caller_count} callers)"
|
|
2032
|
+
elif caller_count == 0 and runtime_calls == 0:
|
|
2033
|
+
finding["confidence"] = _lower_confidence(finding["confidence"])
|
|
2034
|
+
|
|
2035
|
+
runtime_call_threshold = 1500 if not runtime_db_system else 700
|
|
2036
|
+
runtime_hot = (
|
|
2037
|
+
runtime_calls >= runtime_call_threshold
|
|
2038
|
+
or (runtime_p99 is not None and runtime_p99 >= 300)
|
|
2039
|
+
or runtime_error >= 0.02
|
|
2040
|
+
)
|
|
2041
|
+
if runtime_hot:
|
|
2042
|
+
finding["confidence"] = _boost_confidence(finding["confidence"])
|
|
2043
|
+
rt_bits = []
|
|
2044
|
+
if runtime_calls:
|
|
2045
|
+
rt_bits.append(f"{runtime_calls} calls")
|
|
2046
|
+
if runtime_p99 is not None:
|
|
2047
|
+
rt_bits.append(f"p99 {runtime_p99:.0f}ms")
|
|
2048
|
+
if runtime_error > 0:
|
|
2049
|
+
rt_bits.append(f"err {runtime_error * 100:.1f}%")
|
|
2050
|
+
if runtime_db_system:
|
|
2051
|
+
rt_bits.append(
|
|
2052
|
+
"db {}{}".format(
|
|
2053
|
+
runtime_db_system,
|
|
2054
|
+
f" {runtime_db_operation}" if runtime_db_operation else "",
|
|
2055
|
+
)
|
|
2056
|
+
)
|
|
2057
|
+
if rt_bits:
|
|
2058
|
+
finding["reason"] += f" (runtime: {', '.join(rt_bits)})"
|
|
2059
|
+
|
|
2060
|
+
if loop_bound_small:
|
|
2061
|
+
finding["confidence"] = _lower_confidence(finding["confidence"])
|
|
2062
|
+
finding["reason"] += " (bounded loop)"
|
|
2063
|
+
|
|
2064
|
+
return finding
|
|
2065
|
+
|
|
2066
|
+
|
|
2067
|
+
def _has_strong_runtime(evidence: dict) -> bool:
|
|
2068
|
+
runtime = evidence.get("runtime") if isinstance(evidence, dict) else None
|
|
2069
|
+
if not isinstance(runtime, dict):
|
|
2070
|
+
return False
|
|
2071
|
+
calls = int(runtime.get("call_count", 0) or 0)
|
|
2072
|
+
p99 = runtime.get("p99_latency_ms")
|
|
2073
|
+
return calls >= 200 or (p99 is not None and p99 >= 200)
|
|
2074
|
+
|
|
2075
|
+
|
|
2076
|
+
def _apply_profile(findings: list[dict], profile: str) -> list[dict]:
|
|
2077
|
+
if profile == _PROFILE_AGGRESSIVE:
|
|
2078
|
+
for f in findings:
|
|
2079
|
+
evidence = f.get("evidence", {})
|
|
2080
|
+
if f.get("confidence") == "low" and (
|
|
2081
|
+
int(evidence.get("signal_count", 0) or 0) >= 2 or _has_strong_runtime(evidence)
|
|
2082
|
+
):
|
|
2083
|
+
f["confidence"] = "medium"
|
|
2084
|
+
return findings
|
|
2085
|
+
|
|
2086
|
+
if profile == _PROFILE_STRICT:
|
|
2087
|
+
strict_findings: list[dict] = []
|
|
2088
|
+
for f in findings:
|
|
2089
|
+
if f.get("confidence") == "low":
|
|
2090
|
+
continue
|
|
2091
|
+
precision = (f.get("precision") or "medium").lower()
|
|
2092
|
+
evidence = f.get("evidence", {})
|
|
2093
|
+
runtime_strong = _has_strong_runtime(evidence)
|
|
2094
|
+
if precision == "low" and not runtime_strong and f.get("confidence") != "high":
|
|
2095
|
+
continue
|
|
2096
|
+
if f.get("confidence") == "high":
|
|
2097
|
+
strict_findings.append(f)
|
|
2098
|
+
continue
|
|
2099
|
+
if int(evidence.get("signal_count", 0) or 0) >= 2 or runtime_strong:
|
|
2100
|
+
strict_findings.append(f)
|
|
2101
|
+
return strict_findings
|
|
2102
|
+
|
|
2103
|
+
return findings
|
|
2104
|
+
|
|
2105
|
+
|
|
2106
|
+
# ---------------------------------------------------------------------------
|
|
2107
|
+
# Detector registry
|
|
2108
|
+
# ---------------------------------------------------------------------------
|
|
2109
|
+
|
|
2110
|
+
_MATH_DETECTORS = [
|
|
2111
|
+
("sorting", "manual-sort", detect_manual_sort),
|
|
2112
|
+
("search-sorted", "linear-scan", detect_linear_search),
|
|
2113
|
+
("membership", "list-scan", detect_list_membership),
|
|
2114
|
+
("string-concat", "loop-concat", detect_string_concat_loop),
|
|
2115
|
+
("unique", "nested-dedup", detect_manual_dedup),
|
|
2116
|
+
("max-min", "manual-loop", detect_manual_maxmin),
|
|
2117
|
+
("accumulation", "manual-sum", detect_manual_accumulation),
|
|
2118
|
+
("manual-power", "loop-multiply", detect_manual_power),
|
|
2119
|
+
("manual-gcd", "manual-gcd", detect_manual_gcd),
|
|
2120
|
+
("fibonacci", "naive-recursive", detect_naive_fibonacci),
|
|
2121
|
+
("nested-lookup", "nested-iteration", detect_nested_lookup),
|
|
2122
|
+
("groupby", "manual-check", detect_manual_groupby),
|
|
2123
|
+
("string-reverse", "manual-reverse", detect_string_reverse),
|
|
2124
|
+
("matrix-mult", "naive-triple", detect_matrix_mult),
|
|
2125
|
+
("busy-wait", "sleep-loop", detect_busy_wait),
|
|
2126
|
+
("regex-in-loop", "compile-per-iter", detect_regex_in_loop),
|
|
2127
|
+
("io-in-loop", "loop-query", detect_io_in_loop),
|
|
2128
|
+
("list-prepend", "insert-front", detect_list_prepend),
|
|
2129
|
+
("sort-to-select", "full-sort", detect_sort_to_select),
|
|
2130
|
+
("loop-lookup", "method-scan", detect_loop_lookup),
|
|
2131
|
+
("branching-recursion", "naive-branching", detect_branching_recursion),
|
|
2132
|
+
("quadratic-string", "augment-concat", detect_quadratic_string),
|
|
2133
|
+
("loop-invariant-call", "repeated-call", detect_loop_invariant_call),
|
|
2134
|
+
]
|
|
2135
|
+
|
|
2136
|
+
|
|
2137
|
+
def _iter_registered_detectors():
|
|
2138
|
+
"""Yield built-in detectors plus plugin-contributed detectors."""
|
|
2139
|
+
for det in _MATH_DETECTORS:
|
|
2140
|
+
yield det
|
|
2141
|
+
|
|
2142
|
+
try:
|
|
2143
|
+
from roam.plugins import get_plugin_detectors
|
|
2144
|
+
|
|
2145
|
+
for task_id, way_id, detect_fn in get_plugin_detectors():
|
|
2146
|
+
if callable(detect_fn):
|
|
2147
|
+
yield (task_id, way_id, detect_fn)
|
|
2148
|
+
except Exception:
|
|
2149
|
+
# Plugin loading errors should not impact built-in detection.
|
|
2150
|
+
return
|
|
2151
|
+
|
|
2152
|
+
|
|
2153
|
+
def run_detectors(
|
|
2154
|
+
conn,
|
|
2155
|
+
task_filter=None,
|
|
2156
|
+
confidence_filter=None,
|
|
2157
|
+
*,
|
|
2158
|
+
profile="balanced",
|
|
2159
|
+
return_meta=False,
|
|
2160
|
+
):
|
|
2161
|
+
"""Run all detectors and return combined findings.
|
|
2162
|
+
|
|
2163
|
+
Parameters
|
|
2164
|
+
----------
|
|
2165
|
+
conn : sqlite3.Connection
|
|
2166
|
+
task_filter : str or None
|
|
2167
|
+
If set, only run the detector for this task_id.
|
|
2168
|
+
confidence_filter : str or None
|
|
2169
|
+
If set, keep only findings with this confidence level.
|
|
2170
|
+
profile : str
|
|
2171
|
+
Precision profile: ``balanced`` (default), ``strict``, ``aggressive``.
|
|
2172
|
+
return_meta : bool
|
|
2173
|
+
When True, returns ``(findings, meta)`` where ``meta`` contains
|
|
2174
|
+
detector execution diagnostics (totals + failures).
|
|
2175
|
+
|
|
2176
|
+
Returns list of finding dicts, or ``(findings, meta)`` when
|
|
2177
|
+
``return_meta=True``.
|
|
2178
|
+
"""
|
|
2179
|
+
findings = []
|
|
2180
|
+
failed_detectors = []
|
|
2181
|
+
executed = 0
|
|
2182
|
+
executed_tasks: list[str] = []
|
|
2183
|
+
for task_id, _way_id, detect_fn in _iter_registered_detectors():
|
|
2184
|
+
if task_filter and task_id != task_filter:
|
|
2185
|
+
continue
|
|
2186
|
+
executed += 1
|
|
2187
|
+
executed_tasks.append(task_id)
|
|
2188
|
+
try:
|
|
2189
|
+
hits = detect_fn(conn)
|
|
2190
|
+
except Exception as exc:
|
|
2191
|
+
failed_detectors.append(
|
|
2192
|
+
{
|
|
2193
|
+
"task_id": task_id,
|
|
2194
|
+
"detector": detect_fn.__name__,
|
|
2195
|
+
"error": str(exc),
|
|
2196
|
+
}
|
|
2197
|
+
)
|
|
2198
|
+
continue
|
|
2199
|
+
dmeta = _detector_meta(task_id)
|
|
2200
|
+
for h in hits:
|
|
2201
|
+
h.setdefault("precision", dmeta["precision"])
|
|
2202
|
+
h.setdefault("impact", dmeta["impact"])
|
|
2203
|
+
h.setdefault("tags", list(dmeta["tags"]))
|
|
2204
|
+
findings.extend(hits)
|
|
2205
|
+
|
|
2206
|
+
profile_key = (profile or _PROFILE_BALANCED).lower()
|
|
2207
|
+
if profile_key not in _VALID_PROFILES:
|
|
2208
|
+
profile_key = _PROFILE_BALANCED
|
|
2209
|
+
|
|
2210
|
+
symbol_ids = _dedupe([f["symbol_id"] for f in findings if f.get("symbol_id")])
|
|
2211
|
+
context_map = _symbol_context(conn, symbol_ids)
|
|
2212
|
+
|
|
2213
|
+
# Apply calibration and enrich findings with semantic evidence.
|
|
2214
|
+
for f in findings:
|
|
2215
|
+
ctx = context_map.get(f["symbol_id"], {})
|
|
2216
|
+
_calibrate_finding(f, ctx)
|
|
2217
|
+
enriched_evidence = _build_evidence(ctx)
|
|
2218
|
+
f["evidence"] = _merge_evidence(f.get("evidence"), enriched_evidence)
|
|
2219
|
+
f["evidence_path"] = _build_evidence_path(f, ctx)
|
|
2220
|
+
score = _impact_score(f, ctx)
|
|
2221
|
+
f["impact_score"] = score
|
|
2222
|
+
f["impact_band"] = _impact_band(score)
|
|
2223
|
+
|
|
2224
|
+
pre_profile_count = len(findings)
|
|
2225
|
+
findings = _apply_profile(findings, profile_key)
|
|
2226
|
+
profile_filtered = pre_profile_count - len(findings)
|
|
2227
|
+
|
|
2228
|
+
if confidence_filter:
|
|
2229
|
+
findings = [f for f in findings if f["confidence"] == confidence_filter]
|
|
2230
|
+
|
|
2231
|
+
if return_meta:
|
|
2232
|
+
meta = {
|
|
2233
|
+
"detectors_executed": executed,
|
|
2234
|
+
"detectors_failed": len(failed_detectors),
|
|
2235
|
+
"failed_detectors": failed_detectors,
|
|
2236
|
+
"profile": profile_key,
|
|
2237
|
+
"profile_filtered": profile_filtered,
|
|
2238
|
+
"detector_metadata": {task_id: _detector_meta(task_id) for task_id in executed_tasks},
|
|
2239
|
+
}
|
|
2240
|
+
return findings, meta
|
|
2241
|
+
|
|
2242
|
+
return findings
|