codecop 0.1.0__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.
Files changed (222) hide show
  1. codecop/__init__.py +7 -0
  2. codecop/access.py +140 -0
  3. codecop/access_postgres.py +284 -0
  4. codecop/advisor.py +1512 -0
  5. codecop/advisor_bench.py +493 -0
  6. codecop/advisor_ch.py +2080 -0
  7. codecop/advisor_view.py +381 -0
  8. codecop/advisors.py +184 -0
  9. codecop/agent.py +221 -0
  10. codecop/agentfacts.py +745 -0
  11. codecop/apply/__init__.py +327 -0
  12. codecop/apply/check.py +344 -0
  13. codecop/apply/cli.py +162 -0
  14. codecop/apply/clickhouse.py +379 -0
  15. codecop/apply/common.py +238 -0
  16. codecop/apply/html.py +264 -0
  17. codecop/apply/patch.py +213 -0
  18. codecop/apply/postgres.py +102 -0
  19. codecop/apply/trial.py +166 -0
  20. codecop/assemble.py +104 -0
  21. codecop/baseline.py +1043 -0
  22. codecop/bench.py +2464 -0
  23. codecop/blockers.py +935 -0
  24. codecop/budget.py +980 -0
  25. codecop/catalog_profile.py +525 -0
  26. codecop/changed.py +261 -0
  27. codecop/cicmd.py +1002 -0
  28. codecop/cli.py +5421 -0
  29. codecop/client.py +729 -0
  30. codecop/coverage.py +1067 -0
  31. codecop/coverage_reasons.py +116 -0
  32. codecop/crashlog.py +70 -0
  33. codecop/datagen.py +766 -0
  34. codecop/datagen_postgres.py +630 -0
  35. codecop/datagen_sqlite.py +323 -0
  36. codecop/dbcli.py +885 -0
  37. codecop/definitions.py +457 -0
  38. codecop/discover/__init__.py +702 -0
  39. codecop/discover/arms.py +160 -0
  40. codecop/discover/base.py +234 -0
  41. codecop/discover/dialect.py +296 -0
  42. codecop/discover/elixir.py +64 -0
  43. codecop/discover/engine_go.py +320 -0
  44. codecop/discover/go.py +1947 -0
  45. codecop/discover/java.py +1528 -0
  46. codecop/discover/loops.py +1671 -0
  47. codecop/discover/named_go.py +258 -0
  48. codecop/discover/origins.py +4565 -0
  49. codecop/discover/origins_ts.py +1584 -0
  50. codecop/discover/orm_django.py +2772 -0
  51. codecop/discover/orm_django_models.py +814 -0
  52. codecop/discover/orm_django_sql.py +662 -0
  53. codecop/discover/orm_ent.py +565 -0
  54. codecop/discover/orm_ex_ecto.py +2138 -0
  55. codecop/discover/orm_go.py +2134 -0
  56. codecop/discover/orm_go_bun.py +602 -0
  57. codecop/discover/orm_go_run.py +636 -0
  58. codecop/discover/orm_go_types.py +1082 -0
  59. codecop/discover/orm_java.py +1450 -0
  60. codecop/discover/orm_jdbi.py +743 -0
  61. codecop/discover/orm_jooq.py +806 -0
  62. codecop/discover/orm_jpa.py +1307 -0
  63. codecop/discover/orm_mybatis.py +730 -0
  64. codecop/discover/orm_py.py +557 -0
  65. codecop/discover/orm_py_peewee.py +1266 -0
  66. codecop/discover/orm_py_prisma.py +298 -0
  67. codecop/discover/orm_rb_activerecord.py +1906 -0
  68. codecop/discover/orm_rust.py +1248 -0
  69. codecop/discover/orm_rust_seaorm.py +734 -0
  70. codecop/discover/orm_sqlalchemy.py +2475 -0
  71. codecop/discover/orm_stats.py +307 -0
  72. codecop/discover/orm_tables.py +29 -0
  73. codecop/discover/orm_ts.py +503 -0
  74. codecop/discover/orm_ts_drizzle.py +697 -0
  75. codecop/discover/orm_ts_knex.py +1117 -0
  76. codecop/discover/orm_ts_kysely.py +861 -0
  77. codecop/discover/orm_ts_prisma.py +1045 -0
  78. codecop/discover/orm_ts_schema.py +169 -0
  79. codecop/discover/orm_ts_sequelize.py +1401 -0
  80. codecop/discover/orm_ts_typeorm.py +1067 -0
  81. codecop/discover/probes.py +323 -0
  82. codecop/discover/python.py +595 -0
  83. codecop/discover/ruby.py +793 -0
  84. codecop/discover/rust.py +2378 -0
  85. codecop/discover/schema.py +520 -0
  86. codecop/discover/schema_ent.py +145 -0
  87. codecop/discover/schema_ts.py +420 -0
  88. codecop/discover/tsresolve.py +257 -0
  89. codecop/discover/typescript.py +1728 -0
  90. codecop/discover/xml_mapper.py +526 -0
  91. codecop/engines/__init__.py +515 -0
  92. codecop/engines/base.py +498 -0
  93. codecop/engines/clickhouse.py +1558 -0
  94. codecop/engines/pg_ddl.py +444 -0
  95. codecop/engines/pg_hints.py +137 -0
  96. codecop/engines/postgres.py +1060 -0
  97. codecop/engines/sqlite.py +742 -0
  98. codecop/families/__init__.py +3 -0
  99. codecop/families/build.py +280 -0
  100. codecop/families/cli.py +177 -0
  101. codecop/families/coverage_hook.py +62 -0
  102. codecop/families/driver.py +221 -0
  103. codecop/families/goslice.py +229 -0
  104. codecop/families/goslice_tool/go.mod +3 -0
  105. codecop/families/goslice_tool/main.go +403 -0
  106. codecop/families/holes.py +451 -0
  107. codecop/families/images/Dockerfile.go +5 -0
  108. codecop/families/images/Dockerfile.python +4 -0
  109. codecop/families/images/Dockerfile.rust +4 -0
  110. codecop/families/isolate.py +171 -0
  111. codecop/families/locate.py +270 -0
  112. codecop/families/model.py +301 -0
  113. codecop/families/plangate.py +271 -0
  114. codecop/families/tagpatch.py +174 -0
  115. codecop/fidelity.py +671 -0
  116. codecop/fixgroups.py +130 -0
  117. codecop/formerly.py +91 -0
  118. codecop/grantscript.py +254 -0
  119. codecop/groupbench.py +1375 -0
  120. codecop/groups.py +594 -0
  121. codecop/groups_view.py +186 -0
  122. codecop/heat.py +1405 -0
  123. codecop/heatcli.py +219 -0
  124. codecop/joins.py +1749 -0
  125. codecop/joins_view.py +127 -0
  126. codecop/kinds/__init__.py +507 -0
  127. codecop/kinds/calls/__init__.py +501 -0
  128. codecop/kinds/calls/extract.py +1097 -0
  129. codecop/kinds/calls/harness.py +408 -0
  130. codecop/kinds/calls/measure.py +342 -0
  131. codecop/kinds/calls/rules.py +139 -0
  132. codecop/kinds/calls/runners/RunCalls.java +167 -0
  133. codecop/kinds/calls/runners/run_go.go +141 -0
  134. codecop/kinds/calls/runners/run_node.js +186 -0
  135. codecop/kinds/calls/runners/run_python.py +319 -0
  136. codecop/kinds/calls/runners/run_rust.rs +200 -0
  137. codecop/kinds/calls/standin.py +340 -0
  138. codecop/kinds/pipeline.py +288 -0
  139. codecop/kinds/regex/__init__.py +1167 -0
  140. codecop/kinds/regex/engines/RegexHarness.java +129 -0
  141. codecop/kinds/regex/engines/run_go.go +294 -0
  142. codecop/kinds/regex/engines/run_node.js +99 -0
  143. codecop/kinds/regex/engines/run_python.py +295 -0
  144. codecop/kinds/regex/engines/run_rust.rs +149 -0
  145. codecop/kinds/regex/extract.py +1438 -0
  146. codecop/kinds/regex/harness.py +235 -0
  147. codecop/kinds/regex/measure.py +270 -0
  148. codecop/kinds/regex/shapes.py +418 -0
  149. codecop/kinds/regex/syntax.py +1721 -0
  150. codecop/kinds/testkind.py +107 -0
  151. codecop/kinds/transaction/__init__.py +228 -0
  152. codecop/kinds/transaction/bind.py +355 -0
  153. codecop/kinds/transaction/measure.py +264 -0
  154. codecop/kinds/transaction/plan.py +462 -0
  155. codecop/kinds/transaction/rules.py +540 -0
  156. codecop/kinds/transaction/sandbox.py +94 -0
  157. codecop/kinds/transaction/scenarios.py +520 -0
  158. codecop/kinds/transaction/schedule.py +483 -0
  159. codecop/kinds/transaction/shapes.py +418 -0
  160. codecop/kinds/transaction/verify.py +293 -0
  161. codecop/live.py +237 -0
  162. codecop/loopbench.py +2071 -0
  163. codecop/loopschema.py +591 -0
  164. codecop/mcpserver.py +120 -0
  165. codecop/mechanism.py +214 -0
  166. codecop/members.py +200 -0
  167. codecop/multi.py +443 -0
  168. codecop/observed.py +1868 -0
  169. codecop/parts.py +102 -0
  170. codecop/patterns.py +830 -0
  171. codecop/patterns_view.py +559 -0
  172. codecop/plangate.py +242 -0
  173. codecop/profile.py +439 -0
  174. codecop/prompts/areas.md +19 -0
  175. codecop/prompts/observed_variants.md +20 -0
  176. codecop/prompts/profile.md +60 -0
  177. codecop/prompts/profile_postgres.md +68 -0
  178. codecop/prompts/profile_sizes.md +26 -0
  179. codecop/prompts/profile_sqlite.md +69 -0
  180. codecop/prompts/rank.md +84 -0
  181. codecop/prompts/rank_postgres.md +96 -0
  182. codecop/prompts/rank_sqlite.md +94 -0
  183. codecop/prompts/scenario_variants.md +20 -0
  184. codecop/rank.py +1473 -0
  185. codecop/realdb/__init__.py +688 -0
  186. codecop/realdb/clickhouse.py +1223 -0
  187. codecop/realdb/facts.py +815 -0
  188. codecop/realdb/locality.py +964 -0
  189. codecop/realdb/locks.py +355 -0
  190. codecop/realdb/match.py +531 -0
  191. codecop/realdb/postgres.py +643 -0
  192. codecop/realdb/ratios.py +77 -0
  193. codecop/realdb/sample.py +126 -0
  194. codecop/relations.py +227 -0
  195. codecop/report.py +1854 -0
  196. codecop/resources.py +332 -0
  197. codecop/resources_view.py +266 -0
  198. codecop/rules/entry_points.toml +1013 -0
  199. codecop/rules/sinks.toml +362 -0
  200. codecop/runsonce.py +8 -0
  201. codecop/sandboxschema.py +555 -0
  202. codecop/scenario_agent.py +172 -0
  203. codecop/scenario_bind.py +507 -0
  204. codecop/scenario_sql.py +971 -0
  205. codecop/scenarios.py +675 -0
  206. codecop/scenarios_view.py +274 -0
  207. codecop/schemacli.py +67 -0
  208. codecop/schemas/areas_output.schema.json +21 -0
  209. codecop/schemas/profile_output.schema.json +362 -0
  210. codecop/schemas/rank_output.schema.json +385 -0
  211. codecop/sizes.py +200 -0
  212. codecop/sqlinfo.py +558 -0
  213. codecop/typedparams.py +576 -0
  214. codecop/verdicts.py +212 -0
  215. codecop/writebench.py +720 -0
  216. codecop/writecost.py +440 -0
  217. codecop/writes.py +1208 -0
  218. codecop-0.1.0.dist-info/METADATA +42 -0
  219. codecop-0.1.0.dist-info/RECORD +222 -0
  220. codecop-0.1.0.dist-info/WHEEL +4 -0
  221. codecop-0.1.0.dist-info/entry_points.txt +2 -0
  222. codecop-0.1.0.dist-info/licenses/LICENSE +21 -0
codecop/heat.py ADDED
@@ -0,0 +1,1405 @@
1
+ """Heat: how hot the code path of a finding is, so findings are ranked and worded by how much they matter in production.
2
+
3
+ A finding of any kind gets `heat` (docs/kinds.md "Heat"; bundle `$defs.heat`):
4
+
5
+ {level: hot | warm | cold | unknown, calls_per_day: estimate or None, range: [low, high] or None,
6
+ confidence: high | medium | low, source: measured | user | agent | inferred | none,
7
+ basis: [{source, code, text, calls_per_day?, range?, evidence?}], words, effect?, rank, proven, schema_version}
8
+
9
+ Sources, strongest first; every one that says something is kept in `basis` so the console can show why:
10
+
11
+ 1. **user, explicit**: `[heat.entries]` in codecop.toml (a route, job, queue consumer, entry name, `file:symbol` or `file:line`
12
+ -> calls per day or a level). An override is the user's decision and wins over everything below.
13
+ 2. **measured**: the pulled database workload (`db_match.json`, `codecop db pull`): executions per statement located to a
14
+ call site. A function that runs a statement N times a day runs at least about N times a day (when the statement is not
15
+ in a loop of that function); propagated along the call graph discovery already built: the finding's own function, the
16
+ functions on its path up to the entry point (`origins[].path`), then the entry points it shares with a measured
17
+ statement reached from that entry point alone. No new data is collected.
18
+ 3. **user, counts**: per-route / per-handler request counts imported from a file (`codecop heat import`: access logs,
19
+ OpenTelemetry JSON, an APM CSV), in one small neutral format (`COUNTS_FORMAT`).
20
+ 4. **agent**: one question for a verified finding whose heat 1-3 and 5 leave unknown: "how often does this run and from
21
+ where?". The answer must cite a `path:line` that exists; an uncited answer is ignored. Capped at warm.
22
+ 5. **inferred** (rules, no agent): the kind of entry point (HTTP route, consumer, job with its schedule text, CLI, start-up,
23
+ migration, test), health checks, admin and set-up routes, middleware on every request, per-item loops, cache-miss-only
24
+ branches, poll loops with their sleep, how many entry points reach it. A rough range with honest confidence.
25
+
26
+ Levels: hot >= `hot_per_day` (10,000) a day, warm >= `warm_per_day` (100), cold below. **No hot label rests on a guess**:
27
+ only a measured rate, a user's figure or a schedule constant in the code can make a finding hot; every other inference and
28
+ the agent's answer stop at warm.
29
+
30
+ Ranking (`rank_key`): findings with a proven gain (state fixed) first, then by heat x gain, both on a log scale
31
+ (log10 calls/day + log10 of the gain in the kind's own unit: ms saved per call, else the measured ratio). Unknown heat sorts
32
+ between warm and cold. A correctness harm (a call that can hang, a lost update) is never pushed down by coldness: its heat
33
+ counts at least as much as unknown heat, because the damage is per occurrence (one hang holds a worker for good), and a rare
34
+ path that hangs still hangs; it is still worded "runs rarely".
35
+ """
36
+
37
+ from __future__ import annotations
38
+
39
+ import csv
40
+ import io
41
+ import json
42
+ import math
43
+ import re
44
+ from dataclasses import dataclass, field
45
+ from datetime import datetime, timezone
46
+ from pathlib import Path
47
+ from typing import Any
48
+
49
+ SCHEMA_VERSION = 1
50
+ LEVELS = ("hot", "warm", "cold", "unknown")
51
+ SOURCES = ("measured", "user", "agent", "inferred", "none")
52
+ CONFIDENCE = ("high", "medium", "low")
53
+ HOT_PER_DAY = 10_000.0
54
+ WARM_PER_DAY = 100.0
55
+ # rank weights on the log10(calls/day) scale for a level without a figure; unknown sorts between warm (>= 2) and cold (< 2)
56
+ LEVEL_WEIGHT = {"hot": 4.5, "warm": 3.0, "cold": 1.0}
57
+ UNKNOWN_WEIGHT = 1.95
58
+ COUNTS_FORMAT = "codecop-heat-counts/1"
59
+ LEVEL_WORDS = {"hot": "Hot", "warm": "Warm", "cold": "Runs rarely", "unknown": "Not known"}
60
+ SOURCE_WORDS = {"measured": "measured in production", "user": "given by you", "agent": "the agent, citing the code",
61
+ "inferred": "inferred from the code", "none": "nothing known"}
62
+ # a measure whose before - after is time saved on every call (the per-day effect is shown for these only, as an estimate)
63
+ PER_CALL_MS = {"time_per_call": "saved per call at the stand-in's simulated round trip", "loop_stall_ms": "less event-loop stall per call"}
64
+ PROMPT_VERSION = "heat-1"
65
+
66
+
67
+ def config_of(root: Path | None) -> dict:
68
+ """codecop.toml of the repository (or the file `CODECOP_CONFIG` names), as cli.load_config reads it."""
69
+ import os
70
+ import tomllib
71
+ from . import formerly
72
+ other = os.environ.get("CODECOP_CONFIG")
73
+ path = Path(other) if other else (formerly.repo_config(root) if root else None)
74
+ try:
75
+ return tomllib.loads(path.read_text()) if path and path.exists() else {}
76
+ except (OSError, ValueError):
77
+ return {}
78
+
79
+
80
+ def settings_of(config: dict | None) -> dict:
81
+ """The `[heat]` table of codecop.toml with its defaults."""
82
+ cfg = dict((config or {}).get("heat") or {}) if isinstance((config or {}).get("heat"), dict) else {}
83
+ out = {"workload": cfg.get("workload") or [], "counts": cfg.get("counts") or [], "entries": cfg.get("entries") or {},
84
+ "ask": cfg.get("ask", True) is not False, "hot_per_day": float(cfg.get("hot_per_day") or HOT_PER_DAY),
85
+ "warm_per_day": float(cfg.get("warm_per_day") or WARM_PER_DAY), "items_per_call": int(cfg.get("items_per_call") or 6)}
86
+ for k in ("workload", "counts"):
87
+ if isinstance(out[k], str):
88
+ out[k] = [out[k]]
89
+ if not isinstance(out["entries"], dict):
90
+ raise ValueError("heat.entries must be a table: target = calls per day, or target = \"hot\" | \"warm\" | \"cold\"")
91
+ for target, value in out["entries"].items():
92
+ if not (_num(value) is not None and float(value) >= 0) and str(value).lower() not in ("hot", "warm", "cold"):
93
+ raise ValueError(f"heat.entries.{target!r}: a number of calls per day (0 or more) or hot, warm or cold")
94
+ return out
95
+
96
+
97
+ def _num(v: Any) -> float | None:
98
+ return float(v) if isinstance(v, (int, float)) and not isinstance(v, bool) and math.isfinite(float(v)) else None
99
+
100
+
101
+ def level_of(per_day: float | None, st: dict | None = None) -> str:
102
+ if per_day is None:
103
+ return "unknown"
104
+ st = st or {}
105
+ if per_day >= float(st.get("hot_per_day") or HOT_PER_DAY):
106
+ return "hot"
107
+ if per_day >= float(st.get("warm_per_day") or WARM_PER_DAY):
108
+ return "warm"
109
+ return "cold"
110
+
111
+
112
+ def per_day_words(n: float | None) -> str:
113
+ """1.2 M, 15 k, 340, 2, 0.3 (a day)."""
114
+ if n is None:
115
+ return "?"
116
+ if n >= 1e6:
117
+ return f"{n / 1e6:.3g} M"
118
+ if n >= 1e4:
119
+ return f"{n / 1e3:.3g} k"
120
+ if n >= 10:
121
+ return f"{n:,.0f}"
122
+ if n >= 1:
123
+ return f"{n:.2g}"
124
+ return f"{n:.1g}"
125
+
126
+
127
+ def _range_words(rng) -> str:
128
+ lo, hi = rng
129
+ return f"{per_day_words(lo)}-{per_day_words(hi)}"
130
+
131
+
132
+ def _duration_words(ms: float) -> str:
133
+ s = ms / 1000.0
134
+ if s >= 3600:
135
+ return f"{s / 3600:.3g} h"
136
+ if s >= 60:
137
+ return f"{s / 60:.3g} min"
138
+ if s >= 1:
139
+ return f"{s:.3g} s"
140
+ return f"{ms:.3g} ms"
141
+
142
+
143
+ # --- what heat reads ---------------------------------------------------------------------------------------------------
144
+
145
+ def _days_of(engine_doc: dict, pulled_at: str | None) -> tuple[float | None, str]:
146
+ """The window a pulled workload covers, in days, and its words: `window_hours`, else since the statistics were reset."""
147
+ wh = _num(engine_doc.get("window_hours"))
148
+ if wh:
149
+ return wh / 24.0, f"a {wh:g} h window"
150
+ since = str(engine_doc.get("since") or "").strip()
151
+ if since:
152
+ try:
153
+ t0 = datetime.fromisoformat(since.replace(" ", "T").replace("+00", "+00:00") if since.endswith("+00") else since.replace(" ", "T"))
154
+ if t0.tzinfo is None:
155
+ t0 = t0.replace(tzinfo=timezone.utc)
156
+ t1 = datetime.fromisoformat(pulled_at) if pulled_at else datetime.now(timezone.utc)
157
+ if t1.tzinfo is None:
158
+ t1 = t1.replace(tzinfo=timezone.utc)
159
+ days = (t1 - t0).total_seconds() / 86400.0
160
+ if days > 0.01:
161
+ return days, f"{days:.1f} d since stats reset"
162
+ except ValueError:
163
+ pass
164
+ return None, ""
165
+
166
+
167
+ def _workload_files(out_dir: Path | None, root: Path | None, extra: list | None) -> list[Path]:
168
+ out: list[Path] = []
169
+ own = [Path(out_dir) / "db_match.json"] if out_dir else []
170
+ for p in own + [Path(x) for x in extra or []]:
171
+ if root is not None and not p.is_absolute() and p not in own:
172
+ p = root / p
173
+ if p.is_dir():
174
+ p = p / "db_match.json"
175
+ if p.exists() and p not in out:
176
+ out.append(p)
177
+ return out
178
+
179
+
180
+ @dataclass
181
+ class Facts:
182
+ """Everything heat reads, loaded once per out dir (`load`)."""
183
+ root: Path | None = None
184
+ settings: dict = field(default_factory=lambda: settings_of(None))
185
+ sites: dict = field(default_factory=dict) # kind site id -> the inventory site (origins with path, loops)
186
+ by_place: dict = field(default_factory=dict) # (file, line) -> a kind site (a finding whose id is not a site's)
187
+ measured: dict = field(default_factory=dict) # query site id -> {per_day, executions, window, shared, file, line, ...}
188
+ by_function: dict = field(default_factory=dict) # (file, symbol) -> [measured]
189
+ by_file: dict = field(default_factory=dict) # file -> [measured]
190
+ by_entry: dict = field(default_factory=dict) # entry keys -> [measured reached only from them, no loop on the way]
191
+ seen_entry: dict = field(default_factory=dict) # entry keys -> [measured reached only from them, through a loop]
192
+ counts: list = field(default_factory=list) # imported request counts: {target, norm, per_day, source, file}
193
+ answers: dict = field(default_factory=dict) # finding id -> the agent's cited answer
194
+ workloads: list = field(default_factory=list) # words per workload file read: engine, window
195
+ _lines: dict = field(default_factory=dict)
196
+
197
+ def lines(self, rel: str) -> list[str]:
198
+ """A repository file's lines (cached; [] when it cannot be read). Never `.env` files or `envs/`."""
199
+ if rel in self._lines:
200
+ return self._lines[rel]
201
+ out: list[str] = []
202
+ if self.root is not None and rel and not re.search(r"(^|/)(\.env[^/]*|envs)(/|$)", rel):
203
+ try:
204
+ p = (self.root / rel).resolve()
205
+ if self.root.resolve() in p.parents and p.stat().st_size < 4_000_000:
206
+ out = p.read_text(errors="replace").splitlines()
207
+ except (OSError, ValueError):
208
+ out = []
209
+ self._lines[rel] = out
210
+ return out
211
+
212
+
213
+ def entry_key(o: dict) -> str:
214
+ return f"{o.get('kind') or ''}|{o.get('name') or ''}|{o.get('file') or ''}:{o.get('line') or ''}"
215
+
216
+
217
+ def load(out_dir: Path | None, *, root: Path | None = None, config: dict | None = None, inventory: dict | None = None,
218
+ workload: list | None = None, verdicts=None) -> Facts:
219
+ """The facts of one out dir: the inventory's sites (kind sites with their paths, query sites with their trace), the
220
+ pulled workload's executions per located statement, the imported counts and the agent's stored answers."""
221
+ st = settings_of(config)
222
+ fx = Facts(root=Path(root) if root else None, settings=st)
223
+ if inventory is None and out_dir is not None and (Path(out_dir) / "inventory.json").exists():
224
+ try:
225
+ inventory = json.loads((Path(out_dir) / "inventory.json").read_text())
226
+ except (OSError, ValueError):
227
+ inventory = None
228
+ inv = inventory or {}
229
+ for sec in (inv.get("kinds") or {}).values():
230
+ for s in (sec or {}).get("sites") or []:
231
+ if isinstance(s, dict) and s.get("id"):
232
+ fx.sites[s["id"]] = s
233
+ fx.by_place.setdefault((s.get("file") or "", int(s.get("line") or 0)), s)
234
+ call_sites = {s.get("id"): s for s in inv.get("call_sites") or [] if isinstance(s, dict) and s.get("id")}
235
+ for p in _workload_files(Path(out_dir) if out_dir else None, fx.root, list(st["workload"]) + list(workload or [])):
236
+ try:
237
+ doc = json.loads(p.read_text())
238
+ except (OSError, ValueError):
239
+ continue
240
+ for engine, e in (doc.get("engines") or {}).items():
241
+ if not isinstance(e, dict):
242
+ continue
243
+ days, window = _days_of(e, doc.get("generated_at"))
244
+ fx.workloads.append({"engine": engine, "window": window, "file": str(p)})
245
+ shared: dict[str, int] = {}
246
+ for q in e.get("queries") or []:
247
+ ids = [i for i in q.get("site_ids") or [] if isinstance(i, str)]
248
+ for i in ids:
249
+ shared[i] = max(shared.get(i, 1), len(ids))
250
+ for sid, m in (e.get("sites") or {}).items():
251
+ if not isinstance(m, dict):
252
+ continue
253
+ n = _num(m.get("executions"))
254
+ per_day = _num(m.get("executions_per_day"))
255
+ if per_day is None and n is not None and days:
256
+ per_day = n / days
257
+ if per_day is None or per_day <= 0:
258
+ continue
259
+ s = call_sites.get(sid) or {}
260
+ rec = {"id": sid, "engine": engine, "per_day": per_day, "executions": n, "window": window, "match": m.get("match") or "",
261
+ "shared": shared.get(sid, 1), "file": s.get("file") or "", "line": s.get("line") or 0, "symbol": s.get("symbol") or "",
262
+ "in_loop": _loop_at_own_function(s), "origins": [o for o in s.get("origins") or [] if isinstance(o, dict)],
263
+ # no loop anywhere between the statement and its entry points: N executions are N entry runs
264
+ "loop_free": not s.get("loop_count") and not s.get("loop_summary") and not s.get("loop_context"),
265
+ "tables": (m.get("tables") or [])[:3]}
266
+ old = fx.measured.get(sid)
267
+ if old is None or old["per_day"] < per_day:
268
+ fx.measured[sid] = rec
269
+ for rec in fx.measured.values():
270
+ if rec["file"]:
271
+ fx.by_file.setdefault(rec["file"], []).append(rec)
272
+ if rec["symbol"]:
273
+ fx.by_function.setdefault((rec["file"], rec["symbol"]), []).append(rec)
274
+ real = [o for o in rec["origins"] if o.get("kind") != "test"]
275
+ # the entry points that reach it (a command-line or canary `main` beside others is a person's run, left out): together
276
+ # they run at least N times a day when no loop sits between them and the statement
277
+ served = [o for o in real if o.get("kind") not in ("cli", "main")] if len(real) > 1 else real
278
+ if served and all(o.get("verified", True) is not False for o in served) and len(real) < 5:
279
+ # (listed origins stop at max_origins: a site with more has others not shown)
280
+ key = frozenset(entry_key(o) for o in served)
281
+ if not rec["in_loop"] and rec["loop_free"]:
282
+ fx.by_entry.setdefault(key, []).append({**rec, "alone": len(real) == 1, "entries": len(served)})
283
+ else: # in a loop: the entry points ran at least once in the window, how often is not known
284
+ fx.seen_entry.setdefault(key, []).append(rec)
285
+ for p in st["counts"]:
286
+ path = Path(p)
287
+ if fx.root is not None and not path.is_absolute():
288
+ path = fx.root / path
289
+ try:
290
+ fx.counts += counts_rows(read_counts(path), str(p))
291
+ except (OSError, ValueError):
292
+ continue
293
+ if verdicts is not None:
294
+ fx.answers = _stored_answers(verdicts)
295
+ return fx
296
+
297
+
298
+ def _loop_at_own_function(site: dict) -> bool:
299
+ ls = site.get("loop_summary") or {}
300
+ return bool(ls) and int(ls.get("hop") or 0) == 0 and ls.get("kind") in ("per-item", "loop", "retry-poll", None)
301
+
302
+
303
+ # --- the neutral counts format and its converters ---------------------------------------------------------------------
304
+
305
+ def read_counts(path: Path) -> dict:
306
+ """A counts file in the neutral format: JSON `{schema, window_hours, source, counts: [{target, count}]}` or CSV with the
307
+ header `target,count[,window_hours]`."""
308
+ text = Path(path).read_text()
309
+ if Path(path).suffix.lower() == ".csv" or not text.lstrip().startswith("{"):
310
+ rows = list(csv.DictReader(io.StringIO(text)))
311
+ if not rows or "target" not in rows[0] or "count" not in rows[0]:
312
+ raise ValueError(f"{path}: a counts CSV needs the columns target,count (and window_hours)")
313
+ wh = next((float(r["window_hours"]) for r in rows if (r.get("window_hours") or "").strip()), None)
314
+ return {"schema": COUNTS_FORMAT, "window_hours": wh or 24.0, "source": Path(path).name,
315
+ "counts": [{"target": r["target"].strip(), "count": float(r["count"])} for r in rows if (r.get("target") or "").strip()]}
316
+ doc = json.loads(text)
317
+ check_counts(doc)
318
+ return doc
319
+
320
+
321
+ def check_counts(doc: Any) -> None:
322
+ if not isinstance(doc, dict) or doc.get("schema") != COUNTS_FORMAT:
323
+ raise ValueError(f"a counts file must say schema {COUNTS_FORMAT!r}")
324
+ wh = _num(doc.get("window_hours"))
325
+ if wh is None or wh <= 0:
326
+ raise ValueError("window_hours must be a number above 0")
327
+ rows = doc.get("counts")
328
+ if not isinstance(rows, list):
329
+ raise ValueError("counts must be a list of {target, count}")
330
+ for r in rows:
331
+ if not isinstance(r, dict) or not isinstance(r.get("target"), str) or not r["target"].strip() or _num(r.get("count")) is None \
332
+ or r["count"] < 0:
333
+ raise ValueError(f"each count needs a target (a route, a handler, an entry name or file:symbol) and a count of 0 or more: {r!r}")
334
+
335
+
336
+ def counts_rows(doc: dict, source: str) -> list[dict]:
337
+ days = float(doc["window_hours"]) / 24.0
338
+ out = []
339
+ for r in doc.get("counts") or []:
340
+ out.append({"target": r["target"], "norm": norm_target(r["target"]), "per_day": float(r["count"]) / days,
341
+ "count": float(r["count"]), "window_hours": float(doc["window_hours"]), "source": doc.get("source") or source,
342
+ "file": source})
343
+ return out
344
+
345
+
346
+ _PARAM = re.compile(r"\{[^}/]*\}|<[^>/]*>|:[A-Za-z_][\w]*|\[[^\]/]*\]")
347
+ _ID_SEG = re.compile(r"^(?:\d+|[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|[0-9a-fA-F]{16,})$")
348
+ _VERBS = ("GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS", "ANY", "WS")
349
+
350
+
351
+ def norm_route(text: str) -> str | None:
352
+ """`GET /api/users/{id}` -> `GET /api/users/{}`; path parameters in any framework's spelling and id-like segments
353
+ (numbers, uuids, long hex) become `{}`. None when the text is not a route."""
354
+ t = str(text or "").strip()
355
+ method = ""
356
+ m = re.match(r"^([A-Za-z]+)\s+(\S+)$", t)
357
+ if m and m.group(1).upper() in _VERBS:
358
+ method, t = m.group(1).upper(), m.group(2)
359
+ if not t.startswith("/"):
360
+ return None
361
+ t = t.split("?", 1)[0].rstrip("/") or "/"
362
+ segs = [("{}" if _PARAM.fullmatch(s) or _ID_SEG.match(s) else _PARAM.sub("{}", s)) for s in t.split("/")]
363
+ return f"{method} {'/'.join(segs)}".strip()
364
+
365
+
366
+ def norm_target(text: str) -> str:
367
+ r = norm_route(text)
368
+ return r if r is not None else str(text or "").strip()
369
+
370
+
371
+ def _route_matches(want: str, have: str) -> bool:
372
+ """A route target against an entry's route: the same path, the same method or the target says none."""
373
+ if not want or not have:
374
+ return False
375
+ wm, _, wp = want.rpartition(" ") if " " in want else ("", "", want)
376
+ hm, _, hp = have.rpartition(" ") if " " in have else ("", "", have)
377
+ if wp != hp and not (hp.endswith(wp) and wp.count("/") >= 2) and not (wp.endswith(hp) and hp.count("/") >= 2):
378
+ return False
379
+ return not wm or not hm or wm == hm or hm == "ANY"
380
+
381
+
382
+ def access_log_counts(lines, window_hours: float | None = None) -> dict:
383
+ """Common / combined access log lines (nginx, Apache, most proxies) -> neutral counts per `METHOD /path` (query strings
384
+ dropped, ids folded to `{}`). The window comes from the first and last timestamps when not given."""
385
+ req = re.compile(r'"([A-Z]+) ([^ "]+)(?: HTTP/[\d.]+)?"')
386
+ ts = re.compile(r"\[(\d{2}/\w{3}/\d{4}:\d{2}:\d{2}:\d{2} [+-]\d{4})\]")
387
+ counts: dict[str, float] = {}
388
+ first = last = None
389
+ for line in lines:
390
+ m = req.search(line)
391
+ if not m:
392
+ continue
393
+ r = norm_route(f"{m.group(1)} {m.group(2)}")
394
+ if r is None:
395
+ continue
396
+ counts[r] = counts.get(r, 0) + 1
397
+ t = ts.search(line)
398
+ if t:
399
+ try:
400
+ when = datetime.strptime(t.group(1), "%d/%b/%Y:%H:%M:%S %z")
401
+ first = when if first is None or when < first else first
402
+ last = when if last is None or when > last else last
403
+ except ValueError:
404
+ pass
405
+ if window_hours is None:
406
+ if first is None or last is None or last <= first:
407
+ raise ValueError("the log has no timestamps to tell its window: pass --window-hours")
408
+ window_hours = max((last - first).total_seconds() / 3600.0, 1 / 60)
409
+ return {"schema": COUNTS_FORMAT, "window_hours": float(window_hours), "source": "access log",
410
+ "counts": [{"target": k, "count": v} for k, v in sorted(counts.items(), key=lambda kv: -kv[1])]}
411
+
412
+
413
+ def otel_counts(doc: dict, window_hours: float | None = None) -> dict:
414
+ """An OpenTelemetry trace export (OTLP JSON: resourceSpans > scopeSpans > spans) -> neutral counts of server and
415
+ consumer spans, by `http.route` (with the method), `rpc.service/rpc.method`, `messaging.destination.name`, else
416
+ `code.filepath:code.function`."""
417
+ counts: dict[str, float] = {}
418
+ t0 = t1 = None
419
+ for rs in doc.get("resourceSpans") or []:
420
+ for ss in (rs or {}).get("scopeSpans") or (rs or {}).get("instrumentationLibrarySpans") or []:
421
+ for sp in (ss or {}).get("spans") or []:
422
+ kind = sp.get("kind")
423
+ if kind not in (2, 5, "SPAN_KIND_SERVER", "SPAN_KIND_CONSUMER"):
424
+ continue
425
+ attrs = {}
426
+ for a in sp.get("attributes") or []:
427
+ v = (a.get("value") or {})
428
+ attrs[a.get("key")] = next((v[k] for k in ("stringValue", "intValue") if k in v), None)
429
+ target = None
430
+ if attrs.get("http.route"):
431
+ target = norm_route(f"{attrs.get('http.request.method') or attrs.get('http.method') or ''} {attrs['http.route']}".strip())
432
+ elif attrs.get("rpc.method"):
433
+ target = f"{attrs.get('rpc.service') or ''}/{attrs['rpc.method']}"
434
+ elif attrs.get("messaging.destination.name"):
435
+ target = str(attrs["messaging.destination.name"])
436
+ elif attrs.get("code.function"):
437
+ target = f"{attrs.get('code.filepath') or ''}:{attrs['code.function']}".lstrip(":")
438
+ if not target:
439
+ continue
440
+ counts[target] = counts.get(target, 0) + 1
441
+ for key, cmp in (("startTimeUnixNano", min), ("endTimeUnixNano", max)):
442
+ v = sp.get(key)
443
+ try:
444
+ v = int(v)
445
+ except (TypeError, ValueError):
446
+ continue
447
+ if key.startswith("start"):
448
+ t0 = v if t0 is None else min(t0, v)
449
+ else:
450
+ t1 = v if t1 is None else max(t1, v)
451
+ if window_hours is None:
452
+ if t0 is None or t1 is None or t1 <= t0:
453
+ raise ValueError("the export has no span times to tell its window: pass --window-hours")
454
+ window_hours = max((t1 - t0) / 3.6e12, 1 / 60)
455
+ return {"schema": COUNTS_FORMAT, "window_hours": float(window_hours), "source": "OpenTelemetry export",
456
+ "counts": [{"target": k, "count": v} for k, v in sorted(counts.items(), key=lambda kv: -kv[1])]}
457
+
458
+
459
+ def apm_csv_counts(text: str, window_hours: float) -> dict:
460
+ """An APM table exported as CSV (Datadog, New Relic, Grafana, ...): the first column named like a route or endpoint
461
+ (route, endpoint, resource, transaction, name, handler) and the first named like a count (count, calls, requests, hits,
462
+ throughput: per window), with an optional method column."""
463
+ rows = list(csv.DictReader(io.StringIO(text)))
464
+ if not rows:
465
+ raise ValueError("the CSV has no rows")
466
+ cols = {c.lower().strip(): c for c in rows[0].keys() if c}
467
+ name = next((cols[c] for c in ("route", "endpoint", "resource", "resource_name", "transaction", "transaction name", "name", "handler",
468
+ "span name") if c in cols), None)
469
+ count = next((cols[c] for c in ("count", "calls", "requests", "hits", "throughput", "request count", "call count") if c in cols), None)
470
+ method = next((cols[c] for c in ("method", "http.method", "verb") if c in cols), None)
471
+ if not name or not count:
472
+ raise ValueError(f"the CSV needs a route/endpoint/name column and a count/calls/requests column (it has {', '.join(rows[0].keys())})")
473
+ counts: dict[str, float] = {}
474
+ for r in rows:
475
+ raw = (r.get(name) or "").strip()
476
+ try:
477
+ n = float(str(r.get(count) or "0").replace(",", ""))
478
+ except ValueError:
479
+ continue
480
+ if not raw:
481
+ continue
482
+ t = norm_target(f"{(r.get(method) or '').strip()} {raw}".strip() if method else raw)
483
+ counts[t] = counts.get(t, 0) + n
484
+ return {"schema": COUNTS_FORMAT, "window_hours": float(window_hours), "source": "APM CSV",
485
+ "counts": [{"target": k, "count": v} for k, v in sorted(counts.items(), key=lambda kv: -kv[1])]}
486
+
487
+
488
+ # --- the agent's answers ------------------------------------------------------------------------------------------------
489
+
490
+ def answer_key(f: dict) -> str:
491
+ from . import verdicts
492
+ import hashlib
493
+ site = f.get("site") or {}
494
+ text = f"{f.get('kind')}|{site.get('file')}|{site.get('symbol')}|{f.get('id')}"
495
+ return verdicts.key("kind_heat", hashlib.sha256(text.encode()).hexdigest()[:16], [], {}, "", "", PROMPT_VERSION)
496
+
497
+
498
+ def _stored_answers(store) -> dict:
499
+ out = {}
500
+ try:
501
+ items = store.data.get("verdicts", {}).items() if hasattr(store, "data") and isinstance(store.data, dict) else []
502
+ except Exception: # noqa: BLE001
503
+ items = []
504
+ for k, v in items:
505
+ if isinstance(v, dict) and v.get("kind") == "kind_heat":
506
+ out[k] = v
507
+ return out
508
+
509
+
510
+ def cited(root: Path | None, ev: Any) -> str:
511
+ """The agent's `path:line` when that line exists in the repository, else ''."""
512
+ m = re.match(r"^\s*([^\s:]+):(\d+)", str(ev or ""))
513
+ if not m or root is None:
514
+ return ""
515
+ try:
516
+ p = (Path(root) / m.group(1)).resolve()
517
+ if Path(root).resolve() not in p.parents:
518
+ return ""
519
+ n = len(p.read_text(errors="replace").splitlines())
520
+ except (OSError, ValueError):
521
+ return ""
522
+ return f"{m.group(1)}:{m.group(2)}" if 1 <= int(m.group(2)) <= n else ""
523
+
524
+
525
+ ANSWER_SCHEMA = {"type": "object", "properties": {"answers": {"type": "array", "items": {"type": "object", "properties": {
526
+ "id": {"type": "string"},
527
+ "calls_per_day": {"type": ["number", "null"], "description": "about how many times a day this line runs in production, or null"},
528
+ "level": {"type": "string", "enum": ["hot", "warm", "cold", "unknown"],
529
+ "description": "hot: 10,000 a day or more; warm: 100 to 10,000; cold: fewer than 100; unknown when the code does not say"},
530
+ "trigger": {"type": "string", "description": "what runs it: request, message, schedule, start-up, command, per item, other"},
531
+ "evidence": {"type": ["string", "null"], "description": "path:line of the route, scheduler, loop, caller or start-up code that shows it"},
532
+ "why": {"type": ["string", "null"]}}, "required": ["id", "level", "evidence"]}}}, "required": ["answers"]}
533
+
534
+
535
+ def prompt_for(items: list[dict]) -> str:
536
+ parts = ["You read code to say how often a line runs in production (read the files; do not run anything). For each item: "
537
+ "how often does this run and from where? Give `level`, `calls_per_day` when the code shows a figure (a schedule, an "
538
+ "interval, a loop over a known number of items), `trigger`, and `evidence` as `path:line` of the line that shows it "
539
+ "(the route, the scheduler or cron text, the loop, the caller, the start-up code). An answer without a `path:line` "
540
+ "that exists is ignored. Say `unknown` when the code does not tell. Never open `.env` files or anything under an "
541
+ "`envs/` directory.", ""]
542
+ for f in items:
543
+ site = f.get("site") or {}
544
+ o = f.get("origin") or {}
545
+ eps = "; ".join(f"{e.get('kind')} {e.get('name')} at {e.get('file')}:{e.get('line')}" for e in (o.get("entry_points") or [])[:3])
546
+ parts.append(f"- id {f['id']}: {site.get('file')}:{site.get('line')} in `{site.get('symbol') or '?'}` ({f.get('kind')}: "
547
+ f"{str(f.get('title') or '')[:120]}). Entry points CodeCop traced: {eps or 'none'}.")
548
+ return "\n".join(parts)
549
+
550
+
551
+ def questions(findings: list[dict], facts: Facts) -> list[dict]:
552
+ """The findings worth one agent question: verified (fixed), heat unknown after every other source, not answered."""
553
+ out = []
554
+ for f in findings:
555
+ h = f.get("heat") or {}
556
+ if (f.get("outcome") or {}).get("state") != "fixed" or h.get("level") != "unknown":
557
+ continue
558
+ if answer_key(f) in facts.answers:
559
+ continue
560
+ out.append(f)
561
+ return out
562
+
563
+
564
+ def ask(findings: list[dict], facts: Facts, runner, store, items_per_call: int = 6, log=None) -> int:
565
+ """One question per finding (batched), through the runner the run budget wraps. Answers are stored per finding in the
566
+ verdict store; a re-run never pays again. Returns how many were asked."""
567
+ todo = questions(findings, facts)
568
+ asked = 0
569
+ for i in range(0, len(todo), max(1, items_per_call)):
570
+ part = todo[i:i + items_per_call]
571
+ if hasattr(runner, "tell"):
572
+ runner.tell("kind_heat", len(part))
573
+ result = runner.run(prompt_for(part), ANSWER_SCHEMA, str(facts.root or "."))
574
+ answers = (getattr(result, "output", None) or {}).get("answers") or []
575
+ by = {str(a.get("id")): a for a in answers if isinstance(a, dict)}
576
+ for f in part:
577
+ a = by.get(str(f["id"]))
578
+ rec = {"kind": "kind_heat", "level": (a or {}).get("level") or "unknown", "calls_per_day": _num((a or {}).get("calls_per_day")),
579
+ "trigger": str((a or {}).get("trigger") or "")[:40], "evidence": str((a or {}).get("evidence") or "")[:200],
580
+ "why": str((a or {}).get("why") or "")[:300]}
581
+ store.put(answer_key(f), rec)
582
+ facts.answers[answer_key(f)] = rec
583
+ asked += len(part)
584
+ if log:
585
+ log(f"heat: asked about {len(part)} findings")
586
+ return asked
587
+
588
+
589
+ # --- schedules in code --------------------------------------------------------------------------------------------------
590
+
591
+ def _cron_count(field_: str, lo: int, hi: int) -> int | None:
592
+ seen: set[int] = set()
593
+ for part in field_.split(","):
594
+ step = 1
595
+ if "/" in part:
596
+ part, s = part.split("/", 1)
597
+ if not s.isdigit() or int(s) == 0:
598
+ return None
599
+ step = int(s)
600
+ if part in ("*", "?", ""):
601
+ a, b = lo, hi
602
+ elif "-" in part:
603
+ x, y = part.split("-", 1)
604
+ if not (x.isdigit() and y.isdigit()):
605
+ return None
606
+ a, b = int(x), int(y)
607
+ elif part.isdigit():
608
+ a = int(part)
609
+ b = a if step == 1 else hi
610
+ else:
611
+ return None
612
+ seen.update(range(a, b + 1, step))
613
+ return len(seen) or None
614
+
615
+
616
+ def cron_per_day(expr: str) -> float | None:
617
+ """Runs a day of a cron expression: 5 fields (minute hour day month weekday), 6 with seconds first, or @hourly-style."""
618
+ e = expr.strip()
619
+ named = {"@yearly": 1 / 365, "@annually": 1 / 365, "@monthly": 1 / 30, "@weekly": 1 / 7, "@daily": 1.0, "@midnight": 1.0, "@hourly": 24.0}
620
+ if e in named:
621
+ return named[e]
622
+ m = re.match(r"^@every\s+((?:\d+(?:\.\d+)?(?:ms|s|m|h))+)$", e)
623
+ if m:
624
+ secs = sum(float(n) * {"ms": 0.001, "s": 1, "m": 60, "h": 3600}[u] for n, u in re.findall(r"(\d+(?:\.\d+)?)(ms|s|m|h)", m.group(1)))
625
+ return 86400.0 / secs if secs > 0 else None
626
+ f = e.split()
627
+ if len(f) not in (5, 6):
628
+ return None
629
+ secs = 1
630
+ if len(f) == 6:
631
+ secs = _cron_count(f[0], 0, 59)
632
+ f = f[1:]
633
+ mins, hours = _cron_count(f[0], 0, 59), _cron_count(f[1], 0, 23)
634
+ if not secs or not mins or not hours:
635
+ return None
636
+ frac = 1.0
637
+ if f[2] not in ("*", "?"):
638
+ n = _cron_count(f[2], 1, 31)
639
+ frac = (n or 31) / 30.4
640
+ elif f[4] not in ("*", "?"):
641
+ n = _cron_count(re.sub(r"[A-Za-z]{3}", "1", f[4]), 0, 7)
642
+ frac = min(n or 7, 7) / 7.0
643
+ if f[3] not in ("*", "?"):
644
+ n = _cron_count(re.sub(r"[A-Za-z]{3}", "1", f[3]), 1, 12)
645
+ frac *= (n or 12) / 12.0
646
+ return secs * mins * hours * frac
647
+
648
+
649
+ _UNIT_S = {"ms": 0.001, "millisecond": 0.001, "milliseconds": 0.001, "s": 1, "sec": 1, "secs": 1, "second": 1, "seconds": 1,
650
+ "m": 60, "min": 60, "mins": 60, "minute": 60, "minutes": 60, "h": 3600, "hour": 3600, "hours": 3600,
651
+ "d": 86400, "day": 86400, "days": 86400}
652
+ _CRON_TEXT = re.compile(r"""["'`](@(?:yearly|annually|monthly|weekly|daily|midnight|hourly)|@every\s+[\dhms.]+|"""
653
+ r"""(?:[\d*/,?-]+\s+){4,5}[\d*/,?A-Za-z-]+)["'`]""")
654
+ _INTERVALS = [
655
+ # Go: time.NewTicker(30 * time.Second), time.Tick(5*time.Minute), time.Sleep(10 * time.Second), Every: 5 * time.Minute
656
+ (re.compile(r"(?:NewTicker|Tick|Sleep|Every:)\s*\(?\s*(\d+(?:\.\d+)?)\s*\*\s*time\.(Millisecond|Second|Minute|Hour)"), "go"),
657
+ (re.compile(r"(?:NewTicker|Tick|Sleep|Every:)\s*\(?\s*time\.(Millisecond|Second|Minute|Hour)\b"), "go1"),
658
+ # Python: asyncio.sleep(60), time.sleep(300), interval=30, seconds=30 / minutes=5 / hours=1 (APScheduler, repeat_every, timedelta)
659
+ (re.compile(r"(?:asyncio\.sleep|time\.sleep|\bsleep)\(\s*(\d+(?:\.\d+)?)\s*\)"), "sleep_s"),
660
+ (re.compile(r"\b(seconds|minutes|hours|days)\s*=\s*(\d+(?:\.\d+)?)"), "kw"),
661
+ # gocron / schedule: Every(5).Minutes(), schedule.every(10).minutes
662
+ (re.compile(r"[Ee]very\(\s*(\d+)\s*\)\.(Seconds?|Minutes?|Hours?|Days?|seconds?|minutes?|hours?|days?)\b"), "every"),
663
+ # JS: setInterval(fn, 60000), setInterval(fn, 60 * 1000)
664
+ (re.compile(r"setInterval\([^,]+,\s*(\d+)\s*(?:\*\s*(\d+)\s*)?(?:\*\s*(\d+)\s*)?\)"), "js"),
665
+ # Celery crontab(minute=0, hour=2)
666
+ (re.compile(r"crontab\(([^)]*)\)"), "crontab"),
667
+ ]
668
+
669
+
670
+ def schedule_in(text: str) -> tuple[float, str] | None:
671
+ """Runs a day stated in one or a few lines of code, with the words of what was read: a cron expression, @every, a
672
+ ticker, a sleep in a poll loop, an interval keyword, setInterval, Celery's crontab."""
673
+ m = _CRON_TEXT.search(text)
674
+ if m:
675
+ n = cron_per_day(m.group(1))
676
+ if n:
677
+ return n, f"schedule {m.group(1)}"
678
+ for rx, how in _INTERVALS:
679
+ m = rx.search(text)
680
+ if not m:
681
+ continue
682
+ secs = None
683
+ if how == "go":
684
+ secs = float(m.group(1)) * {"Millisecond": 0.001, "Second": 1, "Minute": 60, "Hour": 3600}[m.group(2)]
685
+ elif how == "go1":
686
+ secs = {"Millisecond": 0.001, "Second": 1, "Minute": 60, "Hour": 3600}[m.group(1)]
687
+ elif how == "sleep_s":
688
+ secs = float(m.group(1))
689
+ elif how == "kw":
690
+ secs = float(m.group(2)) * _UNIT_S[m.group(1)]
691
+ elif how == "every":
692
+ secs = float(m.group(1)) * _UNIT_S[m.group(2).lower().rstrip("s") + "s" if not m.group(2).lower().endswith("s") else m.group(2).lower()]
693
+ elif how == "js":
694
+ ms = float(m.group(1)) * float(m.group(2) or 1) * float(m.group(3) or 1)
695
+ secs = ms / 1000.0
696
+ elif how == "crontab":
697
+ kw = dict(re.findall(r"(minute|hour|day_of_week|day_of_month|month_of_year)\s*=\s*['\"]?([^,'\")]+)", m.group(1)))
698
+ expr = f"{kw.get('minute', '*')} {kw.get('hour', '*')} {kw.get('day_of_month', '*')} {kw.get('month_of_year', '*')} {kw.get('day_of_week', '*')}"
699
+ n = cron_per_day(expr)
700
+ if n:
701
+ return n, f"crontab {expr}"
702
+ continue
703
+ if secs and secs > 0:
704
+ return 86400.0 / secs, f"every {_secs_words(secs)}"
705
+ return None
706
+
707
+
708
+ def _secs_words(s: float) -> str:
709
+ if s >= 86400 and s % 86400 == 0:
710
+ return f"{s / 86400:g} d"
711
+ if s >= 3600 and s % 3600 == 0:
712
+ return f"{s / 3600:g} h"
713
+ if s >= 60 and s % 60 == 0:
714
+ return f"{s / 60:g} min"
715
+ return f"{s:g} s"
716
+
717
+
718
+ _SCHED_CONTEXT = re.compile(r"schedul|cron|interval|periodic|repeat_every|add_job|beat_schedule|every", re.I)
719
+ _FOREVER = re.compile(r"while\s*\(?\s*(?:True|true|1)\s*\)?\s*:?\s*\{?\s*$|^\s*for\s*\{\s*$|^\s*loop\s*\{\s*$|for\s*\(\s*;\s*;\s*\)")
720
+
721
+
722
+ def declared_schedule(lines: list[str], lo: int, hi: int) -> tuple[float, str, int] | None:
723
+ """A schedule the code declares between two lines (0-based slice): a cron text, @every, crontab(), setInterval, or an
724
+ interval keyword (`Every: 24 * time.Hour`, `minutes=5`) with a schedule word nearby. (runs a day, words, line)."""
725
+ lo, hi = max(0, lo), min(len(lines), hi)
726
+ for i in range(lo, hi):
727
+ text = lines[i]
728
+ if not text.strip():
729
+ continue
730
+ m = _CRON_TEXT.search(text) or re.search(r"crontab\(|setInterval\(|[Ee]very\(\s*\d+\s*\)\.", text)
731
+ near = "\n".join(lines[max(lo, i - 6):i + 1])
732
+ if not m and not (_SCHED_CONTEXT.search(near) and re.search(r"Every:|\b(?:seconds|minutes|hours|days)\s*=", text)):
733
+ continue
734
+ got = schedule_in(text)
735
+ if got:
736
+ paused = " (declared paused at start)" if re.search(r"StartPaused:\s*true|paused\s*=\s*True", "\n".join(lines[i:min(hi, i + 3)])) else ""
737
+ return got[0], got[1] + paused, i + 1
738
+ return None
739
+
740
+
741
+ def forever_loop_sleep(lines: list[str], lo: int, hi: int) -> tuple[float, str, int] | None:
742
+ """The sleep or ticker of a loop that never ends (`while True:`, `for {`, `loop {`) between two lines."""
743
+ lo, hi = max(0, lo), min(len(lines), hi)
744
+ consts = None
745
+ for i in range(lo, hi):
746
+ if _FOREVER.search(lines[i]):
747
+ for j in range(i + 1, min(len(lines), i + 60)):
748
+ if re.search(r"sleep|Sleep|NewTicker|Tick\(|\.C\b|setTimeout", lines[j]):
749
+ text = lines[j]
750
+ m = re.search(r"(?:sleep|Sleep|NewTicker|Tick)\(\s*([A-Za-z_][\w.]*)\s*\)", text)
751
+ if m: # a named interval: the constant's value in the same file (POLL_INTERVAL = 120)
752
+ consts = consts if consts is not None else _file_consts(lines)
753
+ value = consts.get(m.group(1).split(".")[-1])
754
+ if value:
755
+ text = text.replace(m.group(1), value)
756
+ got = schedule_in(text) or schedule_in("\n".join(lines[max(lo, i - 10):i + 1]))
757
+ if got:
758
+ return got[0], got[1], j + 1
759
+ return None
760
+ return None
761
+
762
+
763
+ def _file_consts(lines: list[str]) -> dict[str, str]:
764
+ """Numeric constants of a file: `NAME = 120`, `const name = 30 * time.Second`, `const NAME = 60_000;` -> their text."""
765
+ out = {}
766
+ for text in lines:
767
+ # module level only (a local `backoff = 2` that a retry loop doubles is not an interval), never a backoff or retry
768
+ m = re.match(r"^(?:const\s+|var\s+|let\s+|export\s+const\s+|\s*static\s+final\s+\w+\s+|\t)?([A-Za-z_]\w*)\s*(?::\s*\w+)?\s*=\s*"
769
+ r"([\d_.]+(?:\s*\*\s*(?:[\d_.]+|time\.(?:Millisecond|Second|Minute|Hour)))*)\s*;?\s*(?:#.*|//.*)?$", text)
770
+ if m and not re.search(r"backoff|retry|retries|jitter", m.group(1), re.I):
771
+ out.setdefault(m.group(1), m.group(2).replace("_", ""))
772
+ return out
773
+
774
+
775
+ # --- inference from the repository --------------------------------------------------------------------------------------
776
+
777
+ _HEALTH = re.compile(r"(?:^|/)(?:health|healthz|healthcheck|health-check|ready|readyz|readiness|live|livez|liveness|ping|metrics|status)(?:/|$)", re.I)
778
+ _ADMIN = re.compile(r"(?:^|[/_.-])(?:probe|test|tests|verify|validate|validation|setup|install|config|configs|configure|settings|admin|"
779
+ r"version|versions|updates|upgrade|register|registration|oauth|callback|login|logout|signup|token|exchange|"
780
+ r"import|export|backup|restore|seed|migrate|migration|reindex|rebuild|sync-now|debug|diagnostics|autoplan|"
781
+ r"suggest|preview|onboarding|invite|reset|unload|load|add|delete)(?:[/_.-]|$)", re.I)
782
+ _STARTUP = re.compile(r"(?:^|[._ ])(?:startup|on_startup|lifespan|bootstrap|init|initialize|initialise|setup|configure|load_config|"
783
+ r"create_app|make_app|build_app|register_routes|main)(?:$|[._ (])", re.I)
784
+ _MIDDLEWARE = re.compile(r"middleware|interceptor|before_request|after_request|authenticate|auth_required|get_current_user|"
785
+ r"require_auth|verify_token|current_user|ServeHTTP", re.I)
786
+ _CACHE_MISS = re.compile(r"(?:if\s+(?:not\s+)?[\w.]*(?:cache|cached|memo)\w*\s*(?:is\s+None|==\s*None|:)|"
787
+ r"if\s+[\w.]*(?:cache|cached)\w*\s*(?:==\s*nil|===?\s*(?:null|undefined))|get_or_set|"
788
+ r"lru_cache|functools\.cache\b|@cache\b|@cached|sync\.Once|once\.Do\(|cacheMiss|cache_miss|ttl_cache|TTLCache)", re.I)
789
+ # a memoizing getter: `if b.service != nil { return b.service, nil }`, `if self._client is not None: return self._client`,
790
+ # `if (this.client) return this.client`: what follows the check runs once per process
791
+ _MEMO_RX = re.compile(r"if\s+(\w+(?:\.\w+)+)\s*!=\s*nil\s*\{\s*\n\s*return\s+(\w+(?:\.\w+)+)|"
792
+ r"if\s+((?:self|cls)\.\w+(?:\.\w+)*)\s+is\s+not\s+None\s*:\s*\n\s*return\s+((?:self|cls)\.\w+(?:\.\w+)*)|"
793
+ r"if\s*\(\s*(this\.\w+(?:\.\w+)*)\s*\)\s*\{?\s*\n?\s*return\s+(this\.\w+(?:\.\w+)*)")
794
+
795
+
796
+ class _Memo:
797
+ def __init__(self, m, name):
798
+ self.m, self.name = m, name
799
+
800
+ def start(self):
801
+ return self.m.start()
802
+
803
+ def group(self, i):
804
+ return self.name if i == 1 else None
805
+
806
+
807
+ class _MEMO:
808
+ """`if b.store.Pool != nil { return b.store, nil }`: the checked field is what is returned, or a field of it."""
809
+ @staticmethod
810
+ def search(text: str):
811
+ for m in _MEMO_RX.finditer(text):
812
+ checked, returned = next((m.group(i), m.group(i + 1)) for i in (1, 3, 5) if m.group(i))
813
+ if checked == returned or checked.startswith(returned + "."):
814
+ return _Memo(m, returned)
815
+ return None
816
+ _RANGE = {"http":(100.0, 10_000.0), "consumer": (100.0, 100_000.0), "health": (2_880.0, 86_400.0), "admin": (1.0, 50.0),
817
+ "cli": (0.0, 10.0), "startup": (0.0, 24.0), "test": (0.0, 0.0), "middleware": (1_000.0, 100_000.0)}
818
+
819
+
820
+ def _geo(rng) -> float | None:
821
+ lo, hi = rng
822
+ if hi <= 0:
823
+ return 0.0
824
+ return math.sqrt(max(lo, hi / 1000.0, 0.01) * hi)
825
+
826
+
827
+ def _fn_of_path(entry: str) -> tuple[str, int, int, str] | None:
828
+ m = re.match(r"^(.*?):(\d+)-(\d+) (.*)$", str(entry or ""))
829
+ return (m.group(1), int(m.group(2)), int(m.group(3)), m.group(4)) if m else None
830
+
831
+
832
+ def infer(site: dict, f: dict, facts: Facts) -> dict | None:
833
+ """Rules over the entry points that reach the site, its loops and the code around it. Returns a candidate
834
+ {level, calls_per_day, range, confidence, basis[]} or None when the code tells nothing."""
835
+ st = facts.settings
836
+ origins = [o for o in (site.get("origins") or (f.get("origin") or {}).get("entry_points") or []) if isinstance(o, dict)]
837
+ role = site.get("role") or (f.get("origin") or {}).get("role") or ""
838
+ file = (f.get("site") or {}).get("file") or site.get("file") or ""
839
+ line = int((f.get("site") or {}).get("line") or site.get("line") or 0)
840
+ basis: list[dict] = []
841
+ best = None # (per_day or None, range, level, confidence, code-fact?)
842
+
843
+ def take(rng, level, conf, code, text, evidence="", fact=False, per_day=None):
844
+ nonlocal best
845
+ item = {"source": "inferred", "code": code, "text": text[:160]}
846
+ if rng is not None:
847
+ item["range"] = [round(rng[0], 2), round(rng[1], 2)]
848
+ if per_day is not None:
849
+ item["calls_per_day"] = round(per_day, 3)
850
+ if evidence:
851
+ item["evidence"] = evidence
852
+ basis.append(item)
853
+ # a code fact (a declared schedule) wins; otherwise the hottest entry point: a site reached from a route and a
854
+ # command runs at least as often as the route
855
+ rank = (1 if fact else 0, per_day if per_day is not None else (_geo(rng) or 0.0) if rng is not None else 0.0)
856
+ if best is None or rank > best[5]:
857
+ best = (per_day, rng, level, conf, fact, rank, item)
858
+
859
+ if role in ("test",) or site.get("is_test") or (origins and all(o.get("kind") == "test" for o in origins)):
860
+ take((0.0, 0.0), "cold", "medium", "test", "test code or reached only from tests: never runs in production")
861
+ elif role in ("script", "tool", "migration", "migrations", "cli") and not origins:
862
+ take(_RANGE["cli"], "cold", "low", "script", f"{role} code: runs when someone runs it")
863
+
864
+ # schedules, only where the code declares one: the entry point's registration (a cron text, @every, a Schedule block's
865
+ # interval), the functions on the path (a definition builder holding the schedule), and a forever-loop's sleep in a
866
+ # job's own function or a poll loop around the site. A sleep in a retry loop or a timeout is never a schedule.
867
+ seen_sched = False
868
+ for o in origins[:5]:
869
+ kind, name = o.get("kind") or "", str(o.get("name") or "")
870
+ if kind not in ("job", "workflow", "activity", "consumer", "main"):
871
+ continue
872
+ got, where = None, ""
873
+ ef, el = o.get("file") or "", int(o.get("line") or 0)
874
+ lines = facts.lines(ef)
875
+ if lines and el:
876
+ got = declared_schedule(lines, el - 5, el + 8)
877
+ where = f"{ef}:{got[2]}" if got else ""
878
+ if got is None and name and _CRON_TEXT.search(f'"{name}"'):
879
+ n = schedule_in(f'"{name}"')
880
+ got = (n[0], n[1], el) if n else None
881
+ where = f"{ef}:{el}"
882
+ path = [p for p in (_fn_of_path(x) for x in o.get("path") or []) if p]
883
+ if got is None:
884
+ for pf, ps, pe, _ in path:
885
+ pl = facts.lines(pf)
886
+ if pl and 0 < pe - ps <= 150:
887
+ got = declared_schedule(pl, ps - 1, pe)
888
+ if got:
889
+ where = f"{pf}:{got[2]}"
890
+ break
891
+ if got is None and kind == "job" and path:
892
+ jf, js, je, _ = path[-1]
893
+ jl = facts.lines(jf)
894
+ if jl and 0 < je - js < 400:
895
+ got = forever_loop_sleep(jl, js - 1, je)
896
+ where = f"{jf}:{got[2]}" if got else ""
897
+ if got:
898
+ n, words, _ln = got
899
+ take((n, n), level_of(n, st), "medium", "schedule", f"{kind} {name[:60]}: {words} ({per_day_words(n)}/day)",
900
+ evidence=where, fact=True, per_day=n)
901
+ seen_sched = True
902
+ break
903
+ ls = site.get("loop_summary") or {}
904
+ # a loop that never ends around the site or up its callers (`while True:` ... `sleep(POLL_INTERVAL)`): one pass per sleep
905
+ # only under a background entry point: a request handler's watch loop runs while someone keeps a connection open
906
+ background = [o for o in origins[:5] if o.get("kind") in ("job", "main", "workflow", "activity", "consumer")]
907
+ loops = ([ls] + list(site.get("loop_context") or []) if background and len(background) == len(origins[:5]) else []) \
908
+ + [c for o in background for c in o.get("loop_context") or []]
909
+ for lp in loops:
910
+ if seen_sched:
911
+ break
912
+ if not lp or not (lp.get("kind") == "retry-poll" or lp.get("form") == "infinite") or not lp.get("file") or not lp.get("line"):
913
+ continue
914
+ lines = facts.lines(lp["file"])
915
+ got = forever_loop_sleep(lines, int(lp["line"]) - 1, int(lp["line"]) + 1) if lines else None
916
+ if got:
917
+ n, words, ln = got
918
+ take((n, n), level_of(n, st), "medium", "poll_loop", f"poll loop at {lp['file']}:{lp['line']}: {words} ({per_day_words(n)} passes/day)",
919
+ evidence=f"{lp['file']}:{ln}", fact=True, per_day=n)
920
+ seen_sched = True
921
+
922
+ # the kind of entry point
923
+ for o in origins[:5]:
924
+ kind, name = o.get("kind") or "", str(o.get("name") or "")
925
+ where = f"{o.get('file')}:{o.get('line')}"
926
+ path_syms = " ".join((_fn_of_path(x) or ("", 0, 0, ""))[3] for x in o.get("path") or [])
927
+ if kind == "http":
928
+ route = name.split(" ", 1)[-1]
929
+ if _HEALTH.search(route):
930
+ take(_RANGE["health"], "warm", "low", "health_check", f"health check or metrics route {name[:60]}: polled every few seconds",
931
+ evidence=where)
932
+ elif _ADMIN.search(route) or _ADMIN.search(path_syms.split(" ")[-1] if path_syms else ""):
933
+ word = (_ADMIN.search(route) or _ADMIN.search(path_syms)).group(0).strip("/_.-")
934
+ take(_RANGE["admin"], "cold", "low", "admin_route", f"route {name[:60]}: a person triggers it ({word})", evidence=where)
935
+ elif _MIDDLEWARE.search(path_syms):
936
+ take(_RANGE["middleware"], "warm", "low", "middleware", "on every request's path (middleware or auth)", evidence=where)
937
+ else:
938
+ take(_RANGE["http"], "warm", "low", "http_route", f"HTTP route {name[:60]}: once per request; traffic not known", evidence=where)
939
+ elif kind == "consumer":
940
+ take(_RANGE["consumer"], "warm", "low", "consumer", f"consumer {name[:60]}: once per message; volume not known", evidence=where)
941
+ elif kind in ("job", "workflow", "activity") and not seen_sched:
942
+ if _STARTUP.search(name) or _STARTUP.search(path_syms):
943
+ take(_RANGE["startup"], "cold", "low", "startup", f"{kind} {name[:60]} on a start-up path", evidence=where)
944
+ else:
945
+ basis.append({"source": "inferred", "code": "job_no_schedule",
946
+ "text": f"{kind} {name[:60]}: background work; no schedule found in the code"[:160], "evidence": where})
947
+ elif kind == "cli":
948
+ take(_RANGE["cli"], "cold", "medium", "cli", f"command-line entry {name[:60]}: runs when someone runs it", evidence=where)
949
+ elif kind == "main" and not seen_sched:
950
+ if _STARTUP.search(path_syms.replace(" main", "")) and not ls:
951
+ take(_RANGE["startup"], "cold", "low", "startup", "reached from process start-up only", evidence=where)
952
+ else:
953
+ basis.append({"source": "inferred", "code": "main", "text": f"reached from process start ({name[:60]}); how often after that "
954
+ "is not known"[:160], "evidence": where})
955
+
956
+ # a getter that returns what it built before (`if b.service != nil { return b.service }`): the code after the check runs
957
+ # once per process, however often the getter is called
958
+ lines = facts.lines(file)
959
+ if lines and line:
960
+ fn = _function_range(site, f)
961
+ lo = max(0, (fn[0] if fn else line - 12) - 1)
962
+ near = "\n".join(lines[lo:line])
963
+ memo = _MEMO.search(near)
964
+ if memo:
965
+ at = lo + 1 + near[:memo.start()].count("\n")
966
+ item = {"source": "inferred", "code": "memoized", "range": [0.0, 24.0], "evidence": f"{file}:{at}",
967
+ "text": f"once per process: {memo.group(1) or memo.group(2) or memo.group(3)} is returned when already set "
968
+ f"(line {at})"[:160]}
969
+ return {"level": "cold", "calls_per_day": None, "range": [0.0, 24.0], "confidence": "medium", "basis": [item] + basis,
970
+ "why": item["text"] + (f"; the caller runs more often ({basis[0]['text'][:80]})" if basis else "")}
971
+
972
+ # modifiers: a per-item loop, a cache-miss branch, many entry points
973
+ if best is not None:
974
+ per_day, rng, level, conf, fact, rank, item = best
975
+ mods = []
976
+ # a background entry point whose rate the code does not state: a cold guess (a command, an admin route) beside it
977
+ # cannot make the site cold
978
+ live = [o for o in origins[:5] if o.get("kind") in ("job", "workflow", "activity", "consumer", "main")]
979
+ if level == "cold" and not fact and live and not seen_sched and item.get("code") not in ("test",):
980
+ o = live[0]
981
+ basis.remove(item)
982
+ basis.insert(0, item)
983
+ return {"level": "unknown", "calls_per_day": None, "range": None, "confidence": "low", "basis": basis,
984
+ "why": f"also reached from {o.get('kind')} {str(o.get('name'))[:60]}, whose rate the code does not state"}
985
+ if ls.get("kind") == "per-item" or (ls and ls.get("query_per_item")):
986
+ # once per item: more often than the entry point, by a number nobody knows; the figure stays the entry's
987
+ hi = (rng[1] if rng else 0) * 10
988
+ rng = (rng[0], hi) if rng else None
989
+ basis.append({"source": "inferred", "code": "per_item", "text": f"per item of a collection (loop at {ls.get('file')}:{ls.get('line')})"[:160],
990
+ "evidence": f"{ls.get('file')}:{ls.get('line')}"})
991
+ mods.append("at least once per pass, once per item of a collection")
992
+ lines = facts.lines(file)
993
+ if lines and line:
994
+ fn = _function_range(site, f)
995
+ lo = max(0, (fn[0] if fn else line - 12) - 2)
996
+ near = "\n".join(lines[lo:line])
997
+ if _CACHE_MISS.search(near):
998
+ rng = (rng[0] / 100.0, rng[1] / 10.0) if rng else None
999
+ per_day = per_day / 100.0 if per_day is not None else None
1000
+ if per_day is not None:
1001
+ level = level_of(per_day, st)
1002
+ mods.append("only on a cache miss")
1003
+ basis.append({"source": "inferred", "code": "cache_miss", "text": "runs only on a cache miss (a cache check comes first)",
1004
+ "evidence": f"{file}:{lo + 1 + next((i for i, x in enumerate(lines[lo:line]) if _CACHE_MISS.search(x)), 0)}"})
1005
+ n = int(site.get("origin_count") or 0)
1006
+ if n >= 8 and rng and not fact:
1007
+ rng = (rng[0], rng[1] * min(n, 5))
1008
+ basis.append({"source": "inferred", "code": "many_entries", "text": f"reached from {n} entry points"})
1009
+ mods.append(f"reached from {n} entry points")
1010
+ if not fact and rng is not None:
1011
+ level = level_of(_geo(rng), st) # an inferred level follows its range
1012
+ if level == "hot" and not fact:
1013
+ level = "warm" # no hot label rests on a guess
1014
+ basis.remove(item)
1015
+ basis.insert(0, item) # the item the level rests on comes first
1016
+ return {"level": level, "calls_per_day": per_day if fact else None, "range": [round(rng[0], 2), round(rng[1], 2)] if rng else None,
1017
+ "confidence": conf, "basis": basis, "why": "; ".join([item["text"]] + mods)[:200]}
1018
+ if basis:
1019
+ return {"level": "unknown", "calls_per_day": None, "range": None, "confidence": "low", "basis": basis, "why": basis[0]["text"]}
1020
+ return None
1021
+
1022
+
1023
+ def _function_range(site: dict, f: dict) -> tuple[int, int] | None:
1024
+ for o in site.get("origins") or []:
1025
+ p = _fn_of_path((o.get("path") or [None])[0])
1026
+ if p and p[0] == ((f.get("site") or {}).get("file") or site.get("file")):
1027
+ return p[1], p[2]
1028
+ return None
1029
+
1030
+
1031
+ # --- measured: the pulled workload along the call graph -----------------------------------------------------------------
1032
+
1033
+ def _measured_for(site: dict, f: dict, facts: Facts) -> dict | None:
1034
+ """A lower bound from production statements on the finding's path: its own function, the functions between it and the
1035
+ entry point, then a statement reached from the same entry point alone."""
1036
+ file = (f.get("site") or {}).get("file") or site.get("file") or ""
1037
+ symbol = (f.get("site") or {}).get("symbol") or site.get("symbol") or ""
1038
+ st = facts.settings
1039
+ origins = [o for o in site.get("origins") or (f.get("origin") or {}).get("entry_points") or [] if isinstance(o, dict)]
1040
+
1041
+ def usable(recs):
1042
+ return [r for r in recs if not r["in_loop"]]
1043
+
1044
+ def pick(recs, code, conf, text_of):
1045
+ recs = sorted(recs, key=lambda r: -(r["per_day"] / r["shared"]))
1046
+ r = recs[0]
1047
+ n = r["per_day"] / r["shared"]
1048
+ c = conf if r["shared"] == 1 else "low"
1049
+ shared = "" if r["shared"] == 1 else f"; the statement is shared by {r['shared']} call sites, split evenly"
1050
+ return {"per_day": n, "confidence": c, "code": code, "statements": len(recs), "rec": r,
1051
+ "text": (text_of(r, len(recs)) + f" (production, {r['window']}{shared})")[:200]}
1052
+
1053
+ # 1. the finding's own function
1054
+ own = usable(facts.by_function.get((file, symbol), [])) if symbol else []
1055
+ if own:
1056
+ return pick(own, "same_function", "high", lambda r, k: f"{symbol} runs at least {per_day_words(r['per_day'] / r['shared'])}/day: "
1057
+ f"its statement at {r['file']}:{r['line']} ran that often" + (f" ({k} statements)" if k > 1 else ""))
1058
+ # 2. a function between the site and its entry point
1059
+ on_path = []
1060
+ for o in origins:
1061
+ for x in (o.get("path") or [])[1:]:
1062
+ p = _fn_of_path(x)
1063
+ if not p:
1064
+ continue
1065
+ pf, ps, pe, psym = p
1066
+ for r in usable(facts.by_file.get(pf, [])):
1067
+ if ps <= int(r["line"] or 0) <= pe:
1068
+ on_path.append({**r, "_caller": psym})
1069
+ if on_path:
1070
+ return pick(on_path, "caller_on_path", "medium",
1071
+ lambda r, k: f"its caller {r['_caller']} runs at least {per_day_words(r['per_day'] / r['shared'])}/day "
1072
+ f"(statement at {r['file']}:{r['line']})")
1073
+ # 3. the entry points it shares with a statement reached from those entry points only, with no loop on the way: they
1074
+ # run at least N times a day together, and the finding is reached from every one of them
1075
+ mine = {entry_key(o): o for o in origins if o.get("kind") != "test"}
1076
+ hits = []
1077
+ for key, recs in facts.by_entry.items():
1078
+ if key and key <= set(mine):
1079
+ r = max(recs, key=lambda x: x["per_day"] / x["shared"])
1080
+ hits.append((key, r, len(recs)))
1081
+ if hits:
1082
+ key, r, k = max(hits, key=lambda t: (t[1]["per_day"] / t[1]["shared"], -len(t[0])))
1083
+ names = [f"{mine[e].get('kind')} {str(mine[e].get('name'))[:50]}" for e in sorted(key)]
1084
+ conf = "medium" if len(key) == 1 and len(mine) == 1 else "low"
1085
+ what = f"its entry point {names[0]}" if len(names) == 1 else f"its {len(names)} entry points ({', '.join(names[:2])}{', ...' if len(names) > 2 else ''})"
1086
+ return pick([r], "same_entry", conf,
1087
+ lambda r_, k_: f"{what} run at least {per_day_words(r_['per_day'] / r_['shared'])}/day: a statement reached only "
1088
+ f"from {'it' if len(names) == 1 else 'them'}, with no loop, ran that often ({r_['file']}:{r_['line']})")
1089
+ return None
1090
+
1091
+
1092
+ def _seen_in_production(site: dict, f: dict, facts: Facts) -> dict | None:
1093
+ """A basis without a figure: a statement reached only from the finding's entry points ran in the pulled window, through a
1094
+ loop, so the entry points ran but how often is not known. Never decides a level."""
1095
+ origins = [o for o in site.get("origins") or (f.get("origin") or {}).get("entry_points") or [] if isinstance(o, dict)]
1096
+ mine = {entry_key(o) for o in origins if o.get("kind") != "test"}
1097
+ for key, recs in facts.seen_entry.items():
1098
+ if key and key <= mine:
1099
+ r = max(recs, key=lambda x: x["per_day"])
1100
+ return {"source": "measured", "code": "seen_in_window",
1101
+ "text": (f"its entry point{'s' if len(key) > 1 else ''} ran in production: a statement reached only from "
1102
+ f"{'them' if len(key) > 1 else 'it'} ran {per_day_words(r['per_day'])}/day through a loop, so how often "
1103
+ f"the entry runs is not known ({r['window']})")[:200], "evidence": f"{r['file']}:{r['line']}"}
1104
+ return None
1105
+
1106
+
1107
+ def _counts_for(site: dict, f: dict, facts: Facts) -> dict | None:
1108
+ if not facts.counts:
1109
+ return None
1110
+ file = (f.get("site") or {}).get("file") or site.get("file") or ""
1111
+ symbol = (f.get("site") or {}).get("symbol") or site.get("symbol") or ""
1112
+ origins = [o for o in site.get("origins") or (f.get("origin") or {}).get("entry_points") or [] if isinstance(o, dict)]
1113
+ hits = []
1114
+ for c in facts.counts:
1115
+ t = c["norm"]
1116
+ if t in (f"{file}:{symbol}", f"{file}:{(f.get('site') or {}).get('line')}") or (symbol and t == symbol):
1117
+ hits.append((c, "this function"))
1118
+ continue
1119
+ for o in origins:
1120
+ name = str(o.get("name") or "")
1121
+ if (o.get("kind") == "http" and _route_matches(t, norm_route(name) or "")) or t == name or t == f"{o.get('file')}:{o.get('line')}":
1122
+ hits.append((c, f"{o.get('kind')} {name[:60]}"))
1123
+ break
1124
+ if any((p := _fn_of_path(x)) and t in (f"{p[0]}:{p[3]}", p[3]) for x in o.get("path") or []):
1125
+ hits.append((c, f"handler {t[:60]}"))
1126
+ break
1127
+ if not hits:
1128
+ return None
1129
+ total = sum(c["per_day"] for c, _ in hits)
1130
+ c0 = hits[0][0]
1131
+ return {"per_day": total, "confidence": "high" if len(hits) == 1 else "medium", "code": "imported_counts",
1132
+ "text": f"{per_day_words(total)}/day from imported counts of " + ", ".join(w for _, w in hits[:3])
1133
+ + f" ({c0['source']}, {c0['window_hours']:g} h)", "evidence": c0["file"]}
1134
+
1135
+
1136
+ def _override_for(site: dict, f: dict, facts: Facts) -> dict | None:
1137
+ entries = facts.settings.get("entries") or {}
1138
+ if not entries:
1139
+ return None
1140
+ file = (f.get("site") or {}).get("file") or site.get("file") or ""
1141
+ symbol = (f.get("site") or {}).get("symbol") or site.get("symbol") or ""
1142
+ origins = [o for o in site.get("origins") or (f.get("origin") or {}).get("entry_points") or [] if isinstance(o, dict)]
1143
+ for target, value in entries.items():
1144
+ t = norm_target(target)
1145
+ hit = None
1146
+ if target in (f.get("id"), f"{file}:{symbol}", f"{file}:{(f.get('site') or {}).get('line')}"):
1147
+ hit = "this finding" if target == f.get("id") else "this function"
1148
+ else:
1149
+ for o in origins:
1150
+ name = str(o.get("name") or "")
1151
+ if (o.get("kind") == "http" and _route_matches(t, norm_route(name) or "")) or target == name \
1152
+ or target == f"{o.get('file')}:{o.get('line')}":
1153
+ hit = f"{o.get('kind')} {name[:60]}"
1154
+ break
1155
+ if hit:
1156
+ n = _num(value)
1157
+ return {"per_day": n, "level": level_of(n, facts.settings) if n is not None else str(value).lower(), "code": "override",
1158
+ "confidence": "high", "text": f"codecop.toml [heat.entries] {target!r} = {value!r} ({hit})"[:200],
1159
+ "evidence": "codecop.toml"}
1160
+ return None
1161
+
1162
+
1163
+ def _agent_for(f: dict, facts: Facts) -> dict | None:
1164
+ a = facts.answers.get(answer_key(f))
1165
+ if not a:
1166
+ return None
1167
+ ev = cited(facts.root, a.get("evidence"))
1168
+ if not ev or a.get("level") not in ("hot", "warm", "cold"):
1169
+ return {"ignored": True, "text": "the agent's answer cited no line that exists" if not ev else "the agent could not tell"}
1170
+ n = _num(a.get("calls_per_day"))
1171
+ level = level_of(n, facts.settings) if n is not None else a["level"]
1172
+ if level == "hot":
1173
+ level = "warm" # an answer is a claim, not a measurement: no hot label rests on it
1174
+ return {"per_day": n, "level": level, "confidence": "medium" if n is not None else "low", "code": "agent",
1175
+ "text": f"agent, citing {ev}: {a.get('trigger') or a['level']}" + (f", about {per_day_words(n)}/day" if n is not None else "")
1176
+ + (f" ({a['why'][:80]})" if a.get("why") else ""), "evidence": ev}
1177
+
1178
+
1179
+ # --- the gain a finding proved, and the per-day effect --------------------------------------------------------------------
1180
+
1181
+ def gain_of(f: dict) -> dict:
1182
+ """{proven, log, per_call_ms?, measure?, ratio?}: what the finding's verdict measure proved, on a log10 scale."""
1183
+ state = (f.get("outcome") or {}).get("state")
1184
+ proven = state == "fixed"
1185
+ out = {"proven": proven, "log": 0.0}
1186
+ if not proven:
1187
+ return out
1188
+ ms = [m for m in ((f.get("proof") or {}).get("measures") or []) if isinstance(m, dict) and m.get("verdict", True)]
1189
+ for m in ms:
1190
+ b, a = _num(m.get("before")), _num(m.get("after"))
1191
+ if m.get("unit") == "ms" and b is not None and a is not None and b > a and m.get("better", "lower") == "lower":
1192
+ out.update(per_call_ms=round(b - a, 4), measure=m.get("name"), log=math.log10(1 + (b - a)))
1193
+ break
1194
+ else:
1195
+ for m in ms:
1196
+ b, a = _num(m.get("before")), _num(m.get("after"))
1197
+ if b is None or a is None:
1198
+ continue
1199
+ r = (b / a if a else b) if m.get("better", "lower") == "lower" else (a / b if b else a)
1200
+ if r and r > 1:
1201
+ out.update(ratio=round(r, 3), measure=m.get("name"), log=math.log10(r))
1202
+ break
1203
+ if f.get("harm") in ("correctness", "both"):
1204
+ out["log"] = max(out["log"], 1.0)
1205
+ return out
1206
+
1207
+
1208
+ # --- one finding's heat -----------------------------------------------------------------------------------------------
1209
+
1210
+ def compute(f: dict, facts: Facts) -> dict:
1211
+ """The heat of one finding of any kind (query findings: `compute_query`)."""
1212
+ st = facts.settings
1213
+ site = facts.sites.get(f.get("id")) or facts.by_place.get(((f.get("site") or {}).get("file") or "",
1214
+ int((f.get("site") or {}).get("line") or 0))) or {}
1215
+ basis: list[dict] = []
1216
+ chosen = None # (source, level, per_day, range, confidence)
1217
+
1218
+ ov = _override_for(site, f, facts)
1219
+ if ov:
1220
+ basis.append({"source": "user", "code": ov["code"], "text": ov["text"], "evidence": ov["evidence"],
1221
+ **({"calls_per_day": round(ov["per_day"], 3)} if ov["per_day"] is not None else {})})
1222
+ chosen = ("user", ov["level"], ov["per_day"], None, "high", ov["text"])
1223
+ me = _measured_for(site, f, facts)
1224
+ if me:
1225
+ r = me["rec"]
1226
+ basis.append({"source": "measured", "code": me["code"], "text": me["text"], "calls_per_day": round(me["per_day"], 3),
1227
+ "evidence": f"{r['file']}:{r['line']}", "statements": me["statements"]})
1228
+ if chosen is None:
1229
+ lvl = level_of(me["per_day"], st)
1230
+ if lvl == "hot" and r["shared"] > 1:
1231
+ lvl = "warm" # a statement shared by several sites is split evenly: a guess, so never hot
1232
+ chosen = ("measured", lvl, me["per_day"], None, me["confidence"], me["text"])
1233
+ elif facts.seen_entry:
1234
+ seen = _seen_in_production(site, f, facts)
1235
+ if seen:
1236
+ basis.append(seen)
1237
+ co = _counts_for(site, f, facts)
1238
+ if co:
1239
+ basis.append({"source": "user", "code": co["code"], "text": co["text"][:200], "calls_per_day": round(co["per_day"], 3),
1240
+ "evidence": co["evidence"]})
1241
+ if chosen is None:
1242
+ chosen = ("user", level_of(co["per_day"], st), co["per_day"], None, co["confidence"], co["text"])
1243
+ inf = infer(site, f, facts)
1244
+ if inf:
1245
+ basis += inf["basis"]
1246
+ memo = bool(inf["basis"]) and inf["basis"][0].get("code") == "memoized"
1247
+ if (chosen is None or (memo and chosen[0] != "user")) and inf["level"] != "unknown":
1248
+ # a memoizing getter runs the line once per process: a measured rate of the function is not the line's
1249
+ chosen = ("inferred", inf["level"], inf["calls_per_day"], inf["range"], inf["confidence"], inf["why"])
1250
+ unknown_why = inf["why"] if inf["level"] == "unknown" else ""
1251
+ else:
1252
+ unknown_why = ""
1253
+ ag = _agent_for(f, facts)
1254
+ if ag:
1255
+ if ag.get("ignored"):
1256
+ basis.append({"source": "agent", "code": "agent_ignored", "text": ag["text"]})
1257
+ else:
1258
+ basis.append({"source": "agent", "code": "agent", "text": ag["text"][:200], "evidence": ag["evidence"],
1259
+ **({"calls_per_day": round(ag["per_day"], 3)} if ag["per_day"] is not None else {})})
1260
+ if chosen is None:
1261
+ chosen = ("agent", ag["level"], ag["per_day"], None, ag["confidence"], ag["text"])
1262
+ if chosen is None and unknown_why:
1263
+ chosen = ("none", "unknown", None, None, "low", unknown_why)
1264
+ return finish(f, chosen, basis, st)
1265
+
1266
+
1267
+ def finish(f: dict, chosen, basis: list[dict], st: dict | None = None) -> dict:
1268
+ st = st or settings_of(None)
1269
+ source, level, per_day, rng, conf, why = chosen or ("none", "unknown", None, None, "low", "")
1270
+ g = gain_of(f)
1271
+ if per_day is not None:
1272
+ heat_log = math.log10(1 + per_day)
1273
+ elif rng:
1274
+ heat_log = math.log10(1 + (_geo(rng) or 0))
1275
+ heat_log = min(heat_log, 3.99) if level != "hot" else heat_log # a range never sorts as hot
1276
+ else:
1277
+ heat_log = LEVEL_WEIGHT.get(level, UNKNOWN_WEIGHT)
1278
+ if f.get("harm") in ("correctness", "both"):
1279
+ heat_log = max(heat_log, UNKNOWN_WEIGHT) # a hang or a lost update is not pushed down by coldness
1280
+ out = {"schema_version": SCHEMA_VERSION, "level": level, "calls_per_day": round(per_day, 3) if per_day is not None else None,
1281
+ "range": rng, "confidence": conf, "source": source, "why": str(why or "")[:200], "basis": basis[:12], "proven": g["proven"],
1282
+ "gain_log": round(g["log"], 4), "heat_log": round(heat_log, 4), "rank": round(heat_log + g["log"], 4)}
1283
+ if g["proven"] and g.get("per_call_ms") and per_day is not None and g.get("measure") in PER_CALL_MS:
1284
+ out["effect"] = {"per_call_ms": g["per_call_ms"], "per_day_ms": round(per_day * g["per_call_ms"], 1), "measure": g["measure"],
1285
+ "estimate": True}
1286
+ out["words"] = words(out, f)
1287
+ return out
1288
+
1289
+
1290
+ def words(h: dict, f: dict | None = None) -> str:
1291
+ """One line: the level and its basis; a per-day effect only as an estimate with its basis, never as a measured saving."""
1292
+ level = h.get("level") or "unknown"
1293
+ why = h.get("why") or ""
1294
+ if level == "unknown":
1295
+ return "How often this runs is not known" + (f" ({why})" if why else "")
1296
+ if level == "cold":
1297
+ return f"Runs rarely: {why}" if why else "Runs rarely"
1298
+ n = h.get("calls_per_day")
1299
+ head = f"{LEVEL_WORDS[level]}: " + (f"about {per_day_words(n)} calls/day" if n is not None else
1300
+ (f"{_range_words(h['range'])} calls/day (a rough range)" if h.get("range") else "rate not known"))
1301
+ eff = h.get("effect")
1302
+ if eff:
1303
+ head += (f" × {eff['per_call_ms']:.3g} ms {PER_CALL_MS.get(eff['measure'], 'saved per call')} "
1304
+ f"≈ {_duration_words(eff['per_day_ms'])}/day (an estimate)")
1305
+ return f"{head} ({why})" if why else head
1306
+
1307
+
1308
+ def compute_query(f: dict, facts: Facts | None = None) -> dict | None:
1309
+ """A query finding's heat from its own measured executions (`real` / `load`); its ranking is left as it is."""
1310
+ real = f.get("real") if isinstance(f.get("real"), dict) else f.get("load") if isinstance(f.get("load"), dict) else None
1311
+ per_day = None
1312
+ window = ""
1313
+ if real:
1314
+ per_day = _num(real.get("executions_per_day"))
1315
+ if per_day is None and facts is not None:
1316
+ m = facts.measured.get(f.get("id"))
1317
+ per_day = m["per_day"] if m else None
1318
+ window = m["window"] if m else ""
1319
+ elif per_day is not None and _num(real.get("window_hours")):
1320
+ window = f"a {real['window_hours']:g} h window"
1321
+ if per_day is None:
1322
+ if facts is not None and facts.measured.get(f.get("id")):
1323
+ m = facts.measured[f["id"]]
1324
+ per_day, window = m["per_day"], m["window"]
1325
+ if per_day is None:
1326
+ return finish(f, None, [], facts.settings if facts else None)
1327
+ basis = [{"source": "measured", "code": "executions", "calls_per_day": round(per_day, 3),
1328
+ "text": f"this statement ran {per_day_words(per_day)} times/day in production" + (f" ({window})" if window else "")}]
1329
+ return finish(f, ("measured", level_of(per_day, facts.settings if facts else None), per_day, None, "high", basis[0]["text"]), basis,
1330
+ facts.settings if facts else None)
1331
+
1332
+
1333
+ # --- ranking and applying ---------------------------------------------------------------------------------------------
1334
+
1335
+ def rank_key(f: dict):
1336
+ """Sort key: proven gain first, then heat x gain (log scale), then the finding's own order."""
1337
+ h = f.get("heat") or {}
1338
+ return (0 if h.get("proven") else 1, -(h.get("rank") or 0.0))
1339
+
1340
+
1341
+ def annotate(findings: list[dict], facts: Facts, *, sort: bool = True) -> list[dict]:
1342
+ """Every finding of a kind gets `heat`; returned in rank order (a stable sort, so ties keep the kind's order)."""
1343
+ for f in findings:
1344
+ try:
1345
+ f["heat"] = compute(f, facts)
1346
+ except Exception as e: # noqa: BLE001 -- heat must never lose a finding
1347
+ f["heat"] = finish(f, None, [{"source": "none", "code": "error", "text": f"heat could not be worked out ({type(e).__name__})"}],
1348
+ facts.settings)
1349
+ return sorted(findings, key=rank_key) if sort else findings
1350
+
1351
+
1352
+ def summary(findings: list[dict]) -> dict:
1353
+ """Counts by level and by source (the source mix)."""
1354
+ from collections import Counter
1355
+ hs = [f.get("heat") or {} for f in findings]
1356
+ return {"findings": len(hs), "levels": {lv: sum(1 for h in hs if h.get("level") == lv) for lv in LEVELS},
1357
+ "sources": dict(Counter(h.get("source") or "none" for h in hs).most_common())}
1358
+
1359
+
1360
+ def apply_to_report(data: dict, facts: Facts) -> dict:
1361
+ """findings.json: heat on every finding (queries from their measured executions, their order kept), the other kinds
1362
+ re-ranked within each kind and numbered again in that order, and `heat` = the source mix per kind."""
1363
+ from .kinds import QUERY, get
1364
+ findings = data.get("findings") or []
1365
+ queries = [f for f in findings if (f.get("kind") or QUERY) == QUERY]
1366
+ for f in queries:
1367
+ h = compute_query(f, facts)
1368
+ if h is not None:
1369
+ f["heat"] = h
1370
+ out = list(queries)
1371
+ mix = {}
1372
+ by_kind: dict[str, list[dict]] = {}
1373
+ for f in findings:
1374
+ if (f.get("kind") or QUERY) != QUERY:
1375
+ by_kind.setdefault(f["kind"], []).append(f)
1376
+ for name, fs in by_kind.items():
1377
+ fs = annotate(fs, facts)
1378
+ k = get(name)
1379
+ if k is not None:
1380
+ for i, f in enumerate(fs, 1):
1381
+ f["finding"] = f"{k.prefix}-{i:03d}"
1382
+ out += fs
1383
+ mix[name] = summary(fs)
1384
+ if queries:
1385
+ mix[QUERY] = summary(queries)
1386
+ data["findings"] = out
1387
+ if mix:
1388
+ data["heat"] = {"schema_version": SCHEMA_VERSION, "by_kind": mix,
1389
+ "workloads": [{"engine": w["engine"], "window": w["window"]} for w in facts.workloads],
1390
+ "counts": len(facts.counts), "overrides": len(facts.settings.get("entries") or {})}
1391
+ return data
1392
+
1393
+
1394
+ def cross_kind(findings: list[dict]) -> list[dict]:
1395
+ """Every finding of every kind in one order: proven gain first, then heat x gain."""
1396
+ return sorted(findings, key=rank_key)
1397
+
1398
+
1399
+ def register_budget() -> None:
1400
+ from . import budget
1401
+ budget.register_queue_kind("kind_heat", step="kind_heat", label="heat", next_step="ask_agent_about_heat", items_per_call=6,
1402
+ cost=(0.03, 0.08))
1403
+
1404
+
1405
+ register_budget()