radarhound 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.
- radarhound/__init__.py +3 -0
- radarhound/backlog.py +129 -0
- radarhound/botimport.py +222 -0
- radarhound/budget.py +208 -0
- radarhound/calllog.py +70 -0
- radarhound/canary.py +576 -0
- radarhound/chunking.py +167 -0
- radarhound/cli.py +735 -0
- radarhound/config.py +1117 -0
- radarhound/discover.py +649 -0
- radarhound/distill.py +520 -0
- radarhound/doctype.py +705 -0
- radarhound/engines/__init__.py +110 -0
- radarhound/engines/fake.py +94 -0
- radarhound/engines/template.py +637 -0
- radarhound/eval.py +943 -0
- radarhound/feedback.py +290 -0
- radarhound/findings.py +440 -0
- radarhound/follow.py +181 -0
- radarhound/gitlab.py +768 -0
- radarhound/gitutil.py +59 -0
- radarhound/lessons.py +428 -0
- radarhound/mrcontext.py +33 -0
- radarhound/output.py +1296 -0
- radarhound/page.py +380 -0
- radarhound/passes/__init__.py +1 -0
- radarhound/passes/group.py +342 -0
- radarhound/passes/hunt.py +1349 -0
- radarhound/passes/questions.py +2595 -0
- radarhound/passes/verify.py +605 -0
- radarhound/project.py +652 -0
- radarhound/related.py +1284 -0
- radarhound/resources/ask_prefix.md +11 -0
- radarhound/resources/decline.txt +1 -0
- radarhound/resources/group_prefix.md +9 -0
- radarhound/resources/hunt_code_lenses.md +13 -0
- radarhound/resources/hunt_doc_lenses.md +10 -0
- radarhound/resources/hunt_prefix.md +18 -0
- radarhound/resources/opencode-readonly.json +13 -0
- radarhound/resources/probe_group_prefix.md +15 -0
- radarhound/resources/probe_prefix.md +10 -0
- radarhound/resources/profile_prefix.md +12 -0
- radarhound/resources/related_stop.txt +173 -0
- radarhound/resources/router_b.md +8 -0
- radarhound/resources/sibling_prefix.md +1 -0
- radarhound/review.py +2700 -0
- radarhound/router.py +496 -0
- radarhound/rules.py +678 -0
- radarhound/scope.py +241 -0
- radarhound/slash.py +289 -0
- radarhound/snapshot.py +135 -0
- radarhound/stats.py +320 -0
- radarhound/structure.py +803 -0
- radarhound-0.1.0.dist-info/METADATA +239 -0
- radarhound-0.1.0.dist-info/RECORD +59 -0
- radarhound-0.1.0.dist-info/WHEEL +5 -0
- radarhound-0.1.0.dist-info/entry_points.txt +3 -0
- radarhound-0.1.0.dist-info/licenses/LICENSE +21 -0
- radarhound-0.1.0.dist-info/top_level.txt +1 -0
radarhound/__init__.py
ADDED
radarhound/backlog.py
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
"""Backlog matching: mark findings already tracked in backlog files (B31).
|
|
2
|
+
|
|
3
|
+
A markdown backlog file holds rows like ``| X50 | <item> | <why> |``.
|
|
4
|
+
``load_rows`` reads those rows; ``identifiers`` extracts the code-like
|
|
5
|
+
tokens of a text; ``match`` returns the first row sharing enough
|
|
6
|
+
identifiers with a finding.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import re
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
|
|
14
|
+
_ID_RE = re.compile(r"^[A-Z]{0,3}\d+$")
|
|
15
|
+
_BACKTICK_RE = re.compile(r"`([^`]*)`")
|
|
16
|
+
_DOTTED_RE = re.compile(r"[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+)+")
|
|
17
|
+
_WORD_RE = re.compile(r"\w+")
|
|
18
|
+
_CAMEL_RE = re.compile(r"[a-z]+[A-Z]\w*")
|
|
19
|
+
_PASCAL_RE = re.compile(r"[A-Z][a-z0-9]+[A-Z]\w*")
|
|
20
|
+
_SNAKE_RE = re.compile(r"\w+_\w+")
|
|
21
|
+
_FILE_RE = re.compile(r"\w+\.(?:kt|kts|py|php|ts|js|java|xml|sql)")
|
|
22
|
+
|
|
23
|
+
_EXTS = ("kt", "kts", "py", "php", "ts", "js", "java", "xml", "sql")
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def load_rows(root, files):
|
|
27
|
+
"""Read backlog rows from ``files`` under ``root``.
|
|
28
|
+
|
|
29
|
+
Every markdown table line ``| <id> | <rest> |`` whose first cell
|
|
30
|
+
(stripped, ``**`` removed) matches ``^[A-Z]{0,3}\\d+$`` becomes
|
|
31
|
+
``{"id": id, "file": rel, "text": rest}``. Missing or unreadable
|
|
32
|
+
files are skipped silently; header (``| # | ...``) and separator
|
|
33
|
+
(``|---|``) rows never match.
|
|
34
|
+
"""
|
|
35
|
+
rows = []
|
|
36
|
+
base = Path(root)
|
|
37
|
+
for name in files or []:
|
|
38
|
+
try:
|
|
39
|
+
text = (base / str(name)).read_text(
|
|
40
|
+
encoding="utf-8", errors="replace")
|
|
41
|
+
except OSError:
|
|
42
|
+
continue
|
|
43
|
+
for line in text.splitlines():
|
|
44
|
+
stripped = line.strip()
|
|
45
|
+
if not stripped.startswith("|") or not stripped.endswith("|"):
|
|
46
|
+
continue
|
|
47
|
+
cells = [cell.strip() for cell in stripped.strip("|").split("|")]
|
|
48
|
+
if len(cells) < 2:
|
|
49
|
+
continue
|
|
50
|
+
first = cells[0].replace("**", "").strip()
|
|
51
|
+
if not _ID_RE.match(first):
|
|
52
|
+
continue
|
|
53
|
+
rest = " | ".join(cells[1:]).strip()
|
|
54
|
+
rows.append({"id": first, "file": str(name), "text": rest})
|
|
55
|
+
return rows
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def identifiers(text):
|
|
59
|
+
"""Return the lowercased code-like identifier tokens of ``text``.
|
|
60
|
+
|
|
61
|
+
Tokens come from backticked spans (split on non-word characters,
|
|
62
|
+
keeping dotted pairs whole, e.g. ``existingline.quantity``) plus
|
|
63
|
+
code-looking words anywhere: dotted ``a.b``, camelCase
|
|
64
|
+
(``[a-z]+[A-Z]\\w*``), PascalCase with an inner capital
|
|
65
|
+
(``[A-Z][a-z0-9]+[A-Z]\\w*``), snake_case (``\\w+_\\w+``), file
|
|
66
|
+
names (``\\w+\\.(kt|kts|py|php|ts|js|java|xml|sql)``) and their
|
|
67
|
+
stems. Tokens shorter than 4 chars are dropped.
|
|
68
|
+
"""
|
|
69
|
+
out = set()
|
|
70
|
+
text = str(text or "")
|
|
71
|
+
|
|
72
|
+
def _add(token):
|
|
73
|
+
lowered = str(token or "").lower()
|
|
74
|
+
if len(lowered) >= 4:
|
|
75
|
+
out.add(lowered)
|
|
76
|
+
|
|
77
|
+
for span in _BACKTICK_RE.findall(text):
|
|
78
|
+
for token in _DOTTED_RE.findall(span):
|
|
79
|
+
_add(token)
|
|
80
|
+
for token in _WORD_RE.findall(span):
|
|
81
|
+
_add(token)
|
|
82
|
+
for token in _DOTTED_RE.findall(text):
|
|
83
|
+
_add(token)
|
|
84
|
+
for pattern in (_CAMEL_RE, _PASCAL_RE, _SNAKE_RE):
|
|
85
|
+
for token in pattern.findall(text):
|
|
86
|
+
_add(token)
|
|
87
|
+
for token in _FILE_RE.findall(text):
|
|
88
|
+
_add(token)
|
|
89
|
+
_add(token.rsplit(".", 1)[0])
|
|
90
|
+
return out
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def match(finding, rows, min_shared):
|
|
94
|
+
"""Return the first backlog row id matching ``finding``, or None.
|
|
95
|
+
|
|
96
|
+
The finding ids are ``identifiers(title + body + trigger)`` plus
|
|
97
|
+
the stem of ``finding["file"]``. The first row whose identifiers
|
|
98
|
+
share at least ``min_shared`` tokens with the finding, at least
|
|
99
|
+
one of them not the file stem, gives its id. None when ``rows``
|
|
100
|
+
is empty.
|
|
101
|
+
"""
|
|
102
|
+
rows = list(rows or [])
|
|
103
|
+
if not rows:
|
|
104
|
+
return None
|
|
105
|
+
try:
|
|
106
|
+
want = int(min_shared)
|
|
107
|
+
except (TypeError, ValueError):
|
|
108
|
+
return None
|
|
109
|
+
finding = finding or {}
|
|
110
|
+
try:
|
|
111
|
+
text = " ".join(
|
|
112
|
+
str(finding.get(key) or "") for key in ("title", "body", "trigger"))
|
|
113
|
+
except Exception:
|
|
114
|
+
text = ""
|
|
115
|
+
found = set(identifiers(text))
|
|
116
|
+
stem = ""
|
|
117
|
+
try:
|
|
118
|
+
stem = Path(str(finding.get("file") or "")).stem.lower()
|
|
119
|
+
except Exception:
|
|
120
|
+
stem = ""
|
|
121
|
+
if stem:
|
|
122
|
+
found.add(stem)
|
|
123
|
+
for row in rows:
|
|
124
|
+
if not isinstance(row, dict):
|
|
125
|
+
continue
|
|
126
|
+
shared = found & identifiers(row.get("text") or "")
|
|
127
|
+
if len(shared) >= want and (shared - {stem} if stem else shared):
|
|
128
|
+
return row.get("id")
|
|
129
|
+
return None
|
radarhound/botimport.py
ADDED
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
"""Review-bot history import: ``rh learn --import-history`` (B2).
|
|
2
|
+
|
|
3
|
+
Reads a jsonl export, one MR per line::
|
|
4
|
+
|
|
5
|
+
{repo, mr, state, created, title, desc, files: [...],
|
|
6
|
+
findings: [{sev, file, title, human, bot_replies, resolved, ...}],
|
|
7
|
+
...}
|
|
8
|
+
|
|
9
|
+
(the v2 pull adds ``body`` and ``line`` to each finding; used when
|
|
10
|
+
present). Filters: ``repo`` equal to ``--repo`` (default
|
|
11
|
+
``repo_label``), ``since <= mr < before`` when given.
|
|
12
|
+
|
|
13
|
+
Each finding with ``sev`` in Critical/Major/Minor becomes a feedback
|
|
14
|
+
item: ``bot_declined`` if ``human`` matches the DECLINE regex (shipped
|
|
15
|
+
in ``resources/decline.txt``); else ``bot_accepted`` only when there is
|
|
16
|
+
a sign the team acted (``human`` contains "changed this line" or
|
|
17
|
+
``resolved`` is true). A finding with neither is skipped and counted
|
|
18
|
+
as ``unconfirmed`` in the summary line. Idempotent: an item whose
|
|
19
|
+
source is already in ``feedback.jsonl`` is not added again. Then
|
|
20
|
+
distill (when ``distill_every`` is reached).
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
from __future__ import annotations
|
|
24
|
+
|
|
25
|
+
import json
|
|
26
|
+
import re
|
|
27
|
+
import sys
|
|
28
|
+
from datetime import datetime, timezone
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
|
|
31
|
+
SEVERITIES = ("Critical", "Major", "Minor")
|
|
32
|
+
|
|
33
|
+
DECLINE_RESOURCE = "decline.txt"
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _now():
|
|
37
|
+
return datetime.now(timezone.utc).isoformat()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def decline_pattern():
|
|
41
|
+
"""Compile the shipped DECLINE regex (case-insensitive)."""
|
|
42
|
+
path = Path(__file__).resolve().parent / "resources" / DECLINE_RESOURCE
|
|
43
|
+
text = path.read_text(encoding="utf-8").strip()
|
|
44
|
+
return re.compile(text, re.IGNORECASE)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _changed_line(text):
|
|
48
|
+
return "changed this line" in (text or "").lower()
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def finding_kind(finding, decline_re):
|
|
52
|
+
"""Return ``bot_declined`` / ``bot_accepted`` / ``unconfirmed`` / ``skip``.
|
|
53
|
+
|
|
54
|
+
``skip`` means the severity is not Critical/Major/Minor (Trivial
|
|
55
|
+
and below teach nothing).
|
|
56
|
+
"""
|
|
57
|
+
if finding.get("sev") not in SEVERITIES:
|
|
58
|
+
return "skip"
|
|
59
|
+
human = finding.get("human") or ""
|
|
60
|
+
if decline_re.search(human):
|
|
61
|
+
return "bot_declined"
|
|
62
|
+
if _changed_line(human) or finding.get("resolved") is True:
|
|
63
|
+
return "bot_accepted"
|
|
64
|
+
return "unconfirmed"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _entry_head_sha(entry):
|
|
68
|
+
"""Return the head sha for an import row ("" when absent)."""
|
|
69
|
+
if not isinstance(entry, dict):
|
|
70
|
+
return ""
|
|
71
|
+
for key in ("head_sha", "head", "sha"):
|
|
72
|
+
val = entry.get(key)
|
|
73
|
+
if isinstance(val, str) and val.strip():
|
|
74
|
+
return val.strip()
|
|
75
|
+
diff_refs = entry.get("diff_refs")
|
|
76
|
+
if isinstance(diff_refs, dict):
|
|
77
|
+
for key in ("head_sha", "head", "sha"):
|
|
78
|
+
val = diff_refs.get(key)
|
|
79
|
+
if isinstance(val, str) and val.strip():
|
|
80
|
+
return val.strip()
|
|
81
|
+
return ""
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _human_declined(human, decline_re):
|
|
85
|
+
"""True when a human reply declines (regex or Declined/Declining)."""
|
|
86
|
+
text = str(human or "")
|
|
87
|
+
if decline_re.search(text):
|
|
88
|
+
return True
|
|
89
|
+
stripped = text.lstrip()
|
|
90
|
+
return stripped.startswith("Declined") or stripped.startswith("Declining")
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def import_file(root, path, cfg=None, repo=None, since=None, before=None,
|
|
94
|
+
memory_dir=None):
|
|
95
|
+
"""Import one review-bot history jsonl file; returns a summary dict.
|
|
96
|
+
|
|
97
|
+
Idempotent; runs distillation afterwards when ``distill_every`` is
|
|
98
|
+
reached. Prints a summary line.
|
|
99
|
+
"""
|
|
100
|
+
from . import config as config_mod
|
|
101
|
+
from . import doctype as doctype_mod
|
|
102
|
+
from . import feedback as feedback_mod
|
|
103
|
+
|
|
104
|
+
if cfg is None:
|
|
105
|
+
cfg = config_mod.load(root)
|
|
106
|
+
want_repo = repo if repo is not None else getattr(
|
|
107
|
+
cfg, "repo_label", "app")
|
|
108
|
+
decline_re = decline_pattern()
|
|
109
|
+
existing_sources = {
|
|
110
|
+
item.get("source")
|
|
111
|
+
for item in feedback_mod.load_feedback(root, memory_dir)
|
|
112
|
+
if item.get("source")
|
|
113
|
+
}
|
|
114
|
+
added = 0
|
|
115
|
+
unconfirmed = 0
|
|
116
|
+
skipped = 0
|
|
117
|
+
for line in Path(path).read_text(encoding="utf-8").splitlines():
|
|
118
|
+
if not line.strip():
|
|
119
|
+
continue
|
|
120
|
+
try:
|
|
121
|
+
entry = json.loads(line)
|
|
122
|
+
except ValueError:
|
|
123
|
+
continue
|
|
124
|
+
if not isinstance(entry, dict):
|
|
125
|
+
continue
|
|
126
|
+
if entry.get("repo") != want_repo:
|
|
127
|
+
continue
|
|
128
|
+
try:
|
|
129
|
+
mr = int(entry.get("mr"))
|
|
130
|
+
except (TypeError, ValueError):
|
|
131
|
+
continue
|
|
132
|
+
if since is not None and mr < since:
|
|
133
|
+
continue
|
|
134
|
+
if before is not None and mr >= before:
|
|
135
|
+
continue
|
|
136
|
+
row_head = _entry_head_sha(entry)
|
|
137
|
+
findings = entry.get("findings") or []
|
|
138
|
+
for index, finding in enumerate(findings):
|
|
139
|
+
if not isinstance(finding, dict):
|
|
140
|
+
continue
|
|
141
|
+
kind = finding_kind(finding, decline_re)
|
|
142
|
+
if kind == "skip":
|
|
143
|
+
skipped += 1
|
|
144
|
+
continue
|
|
145
|
+
source = "%s!%d#%d" % (want_repo, mr, index)
|
|
146
|
+
if source in existing_sources:
|
|
147
|
+
continue
|
|
148
|
+
human = finding.get("human") or ""
|
|
149
|
+
doc_miss_reason = ""
|
|
150
|
+
if row_head and finding.get("file"):
|
|
151
|
+
try:
|
|
152
|
+
prose_info = doctype_mod.doc_prose_info(
|
|
153
|
+
root, row_head, finding.get("file"), cfg)
|
|
154
|
+
except Exception:
|
|
155
|
+
prose_info = None
|
|
156
|
+
if prose_info is not None and prose_info[0]:
|
|
157
|
+
if not _human_declined(human, decline_re):
|
|
158
|
+
doc_miss_reason = "doc classified prose (score %d)" % (
|
|
159
|
+
prose_info[1],)
|
|
160
|
+
if doc_miss_reason:
|
|
161
|
+
miss_item = {
|
|
162
|
+
"ts": _now(),
|
|
163
|
+
"kind": "miss",
|
|
164
|
+
"fp": None,
|
|
165
|
+
"file": finding.get("file"),
|
|
166
|
+
"title": finding.get("title"),
|
|
167
|
+
"body": finding.get("body") or "",
|
|
168
|
+
"severity": finding.get("sev"),
|
|
169
|
+
"reason": doc_miss_reason,
|
|
170
|
+
"source": source,
|
|
171
|
+
"lessons": [],
|
|
172
|
+
"distilled": False,
|
|
173
|
+
}
|
|
174
|
+
feedback_mod.append_feedback(root, miss_item, memory_dir)
|
|
175
|
+
existing_sources.add(source)
|
|
176
|
+
added += 1
|
|
177
|
+
continue
|
|
178
|
+
if kind == "unconfirmed":
|
|
179
|
+
unconfirmed += 1
|
|
180
|
+
continue
|
|
181
|
+
item = {
|
|
182
|
+
"ts": _now(),
|
|
183
|
+
"kind": kind,
|
|
184
|
+
"fp": None,
|
|
185
|
+
"file": finding.get("file"),
|
|
186
|
+
"title": finding.get("title"),
|
|
187
|
+
"body": finding.get("body") or "",
|
|
188
|
+
"severity": finding.get("sev"),
|
|
189
|
+
"reason": human[:300] if kind == "bot_declined" else "",
|
|
190
|
+
"source": source,
|
|
191
|
+
"lessons": [],
|
|
192
|
+
"distilled": False,
|
|
193
|
+
}
|
|
194
|
+
feedback_mod.append_feedback(root, item, memory_dir)
|
|
195
|
+
existing_sources.add(source)
|
|
196
|
+
added += 1
|
|
197
|
+
from . import feedback as feedback_mod2
|
|
198
|
+
|
|
199
|
+
distill_summary = feedback_mod2.maybe_distill(root, cfg, memory_dir)
|
|
200
|
+
distill_failed = 0
|
|
201
|
+
if isinstance(distill_summary, dict):
|
|
202
|
+
try:
|
|
203
|
+
distill_failed = int(distill_summary.get("failed", 0))
|
|
204
|
+
except (TypeError, ValueError):
|
|
205
|
+
distill_failed = 0
|
|
206
|
+
if distill_failed:
|
|
207
|
+
print(
|
|
208
|
+
"imported %d items (%d unconfirmed, %d skipped non-material; "
|
|
209
|
+
"distill: %d batches failed)"
|
|
210
|
+
% (added, unconfirmed, skipped, distill_failed)
|
|
211
|
+
)
|
|
212
|
+
else:
|
|
213
|
+
print(
|
|
214
|
+
"imported %d items (%d unconfirmed, %d skipped non-material)"
|
|
215
|
+
% (added, unconfirmed, skipped)
|
|
216
|
+
)
|
|
217
|
+
return {"added": added, "unconfirmed": unconfirmed, "skipped": skipped,
|
|
218
|
+
"distill_failed": distill_failed,
|
|
219
|
+
"distill": distill_summary}
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
__all__ = ["decline_pattern", "finding_kind", "import_file"]
|
radarhound/budget.py
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
"""Budgets: stop scheduling new engine calls when over budget (B1b)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import time
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _base_number(value):
|
|
9
|
+
"""Return ``value`` as a number, or None when it is not one."""
|
|
10
|
+
if isinstance(value, bool):
|
|
11
|
+
return None
|
|
12
|
+
if isinstance(value, (int, float)):
|
|
13
|
+
return value
|
|
14
|
+
return None
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def effective_max_calls(max_calls, calls_per_file, n_files, ceiling):
|
|
18
|
+
"""Return the call budget scaled by the range size (B15).
|
|
19
|
+
|
|
20
|
+
``min(max(max_calls, calls_per_file * n_files),
|
|
21
|
+
max(ceiling, max_calls))``; any bad input falls back to
|
|
22
|
+
``max_calls``. ``calls_per_file = 0`` turns scaling off.
|
|
23
|
+
"""
|
|
24
|
+
try:
|
|
25
|
+
base = int(max_calls)
|
|
26
|
+
except (TypeError, ValueError):
|
|
27
|
+
return max_calls
|
|
28
|
+
if isinstance(max_calls, bool):
|
|
29
|
+
return max_calls
|
|
30
|
+
per = _base_number(calls_per_file)
|
|
31
|
+
if per is None or per < 0:
|
|
32
|
+
return base
|
|
33
|
+
try:
|
|
34
|
+
count = int(n_files)
|
|
35
|
+
except (TypeError, ValueError):
|
|
36
|
+
return base
|
|
37
|
+
if isinstance(n_files, bool) or count < 0:
|
|
38
|
+
return base
|
|
39
|
+
cap = _base_number(ceiling)
|
|
40
|
+
if cap is None:
|
|
41
|
+
return base
|
|
42
|
+
if per == 0:
|
|
43
|
+
scaled = base
|
|
44
|
+
else:
|
|
45
|
+
scaled = max(base, per * count)
|
|
46
|
+
return min(scaled, max(cap, base))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def effective_max_minutes(max_minutes, minutes_per_file, n_files, ceiling):
|
|
50
|
+
"""Return the time budget scaled by the range size (B15).
|
|
51
|
+
|
|
52
|
+
Same formula as :func:`effective_max_calls`; any bad input
|
|
53
|
+
falls back to ``max_minutes``. ``minutes_per_file = 0`` off.
|
|
54
|
+
"""
|
|
55
|
+
if isinstance(max_minutes, bool):
|
|
56
|
+
return max_minutes
|
|
57
|
+
try:
|
|
58
|
+
base = float(max_minutes)
|
|
59
|
+
except (TypeError, ValueError):
|
|
60
|
+
return max_minutes
|
|
61
|
+
per = _base_number(minutes_per_file)
|
|
62
|
+
if per is None or per < 0:
|
|
63
|
+
return base
|
|
64
|
+
try:
|
|
65
|
+
count = int(n_files)
|
|
66
|
+
except (TypeError, ValueError):
|
|
67
|
+
return base
|
|
68
|
+
if isinstance(n_files, bool) or count < 0:
|
|
69
|
+
return base
|
|
70
|
+
cap = _base_number(ceiling)
|
|
71
|
+
if cap is None:
|
|
72
|
+
return base
|
|
73
|
+
if per == 0:
|
|
74
|
+
scaled = base
|
|
75
|
+
else:
|
|
76
|
+
scaled = max(base, per * count)
|
|
77
|
+
result = min(scaled, max(cap, base))
|
|
78
|
+
if isinstance(result, float) and result.is_integer():
|
|
79
|
+
return int(result)
|
|
80
|
+
return result
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
class Budget:
|
|
84
|
+
"""Track ``max_calls_per_review`` and ``max_minutes``.
|
|
85
|
+
|
|
86
|
+
``check()`` returns a reason string when no further call may be
|
|
87
|
+
scheduled, else None. ``note_call()`` records one completed call.
|
|
88
|
+
"""
|
|
89
|
+
|
|
90
|
+
def __init__(self, max_calls, max_minutes, started=None,
|
|
91
|
+
fail_streak_limit=0):
|
|
92
|
+
try:
|
|
93
|
+
self.max_calls = int(max_calls)
|
|
94
|
+
except (TypeError, ValueError):
|
|
95
|
+
self.max_calls = 40
|
|
96
|
+
try:
|
|
97
|
+
self.max_minutes = float(max_minutes)
|
|
98
|
+
except (TypeError, ValueError):
|
|
99
|
+
self.max_minutes = 30.0
|
|
100
|
+
try:
|
|
101
|
+
self.fail_streak_limit = int(fail_streak_limit)
|
|
102
|
+
except (TypeError, ValueError):
|
|
103
|
+
self.fail_streak_limit = 0
|
|
104
|
+
self.started = time.monotonic() if started is None else started
|
|
105
|
+
self.calls_made = 0
|
|
106
|
+
self.hit = None
|
|
107
|
+
self.fail_streak = 0
|
|
108
|
+
|
|
109
|
+
def note_hit(self, reason):
|
|
110
|
+
"""Remember the first budget-stop reason."""
|
|
111
|
+
if self.hit is None and reason:
|
|
112
|
+
self.hit = reason
|
|
113
|
+
|
|
114
|
+
def _call_limit(self, reserve_pct=0):
|
|
115
|
+
"""Return the call limit for a reserve percentage."""
|
|
116
|
+
try:
|
|
117
|
+
reserve = int(reserve_pct)
|
|
118
|
+
except (TypeError, ValueError):
|
|
119
|
+
reserve = 0
|
|
120
|
+
if reserve < 0:
|
|
121
|
+
reserve = 0
|
|
122
|
+
if reserve > 100:
|
|
123
|
+
reserve = 100
|
|
124
|
+
call_limit = self.max_calls
|
|
125
|
+
try:
|
|
126
|
+
call_limit = self.max_calls * (100 - reserve) // 100
|
|
127
|
+
if reserve > 0 and reserve < 100 and self.max_calls >= 1:
|
|
128
|
+
if call_limit < 1:
|
|
129
|
+
call_limit = 1
|
|
130
|
+
except (TypeError, ValueError):
|
|
131
|
+
pass
|
|
132
|
+
return call_limit
|
|
133
|
+
|
|
134
|
+
def calls_left(self, reserve_pct=0):
|
|
135
|
+
"""Return how many calls may still be scheduled (never below 0)."""
|
|
136
|
+
try:
|
|
137
|
+
limit = int(self._call_limit(reserve_pct))
|
|
138
|
+
except Exception:
|
|
139
|
+
limit = self.max_calls
|
|
140
|
+
try:
|
|
141
|
+
left = int(limit) - int(self.calls_made)
|
|
142
|
+
except Exception:
|
|
143
|
+
return 0
|
|
144
|
+
if left < 0:
|
|
145
|
+
return 0
|
|
146
|
+
return left
|
|
147
|
+
|
|
148
|
+
def note_outcome(self, rc, answer_chars):
|
|
149
|
+
"""Record one finished call's outcome for the fail streak.
|
|
150
|
+
|
|
151
|
+
A call is failed when ``rc != 0`` or ``answer_chars == 0``;
|
|
152
|
+
bad inputs count as failed. A failed call adds 1 to
|
|
153
|
+
``fail_streak``, any other call resets it to 0. Never raises.
|
|
154
|
+
"""
|
|
155
|
+
try:
|
|
156
|
+
failed = False
|
|
157
|
+
try:
|
|
158
|
+
if int(rc) != 0:
|
|
159
|
+
failed = True
|
|
160
|
+
except (TypeError, ValueError):
|
|
161
|
+
failed = True
|
|
162
|
+
try:
|
|
163
|
+
if int(answer_chars) == 0:
|
|
164
|
+
failed = True
|
|
165
|
+
except (TypeError, ValueError):
|
|
166
|
+
failed = True
|
|
167
|
+
if failed:
|
|
168
|
+
self.fail_streak = self.fail_streak + 1
|
|
169
|
+
else:
|
|
170
|
+
self.fail_streak = 0
|
|
171
|
+
except Exception:
|
|
172
|
+
pass
|
|
173
|
+
|
|
174
|
+
def check(self, reserve_pct=0):
|
|
175
|
+
"""Return a budget-hit reason, or None when calls may continue."""
|
|
176
|
+
try:
|
|
177
|
+
limit = int(self.fail_streak_limit)
|
|
178
|
+
except (TypeError, ValueError):
|
|
179
|
+
limit = 0
|
|
180
|
+
try:
|
|
181
|
+
streak = int(self.fail_streak)
|
|
182
|
+
except (TypeError, ValueError):
|
|
183
|
+
streak = 0
|
|
184
|
+
if limit > 0 and streak >= limit:
|
|
185
|
+
return "engine failing: %d calls in a row failed" % streak
|
|
186
|
+
try:
|
|
187
|
+
reserve = int(reserve_pct)
|
|
188
|
+
except (TypeError, ValueError):
|
|
189
|
+
reserve = 0
|
|
190
|
+
if reserve < 0:
|
|
191
|
+
reserve = 0
|
|
192
|
+
if reserve > 100:
|
|
193
|
+
reserve = 100
|
|
194
|
+
call_limit = self._call_limit(reserve)
|
|
195
|
+
if self.calls_made >= call_limit:
|
|
196
|
+
return "max_calls_per_review reached (%d)" % self.max_calls
|
|
197
|
+
elapsed_minutes = (time.monotonic() - self.started) / 60.0
|
|
198
|
+
try:
|
|
199
|
+
minute_limit = float(self.max_minutes) * (100 - reserve) / 100.0
|
|
200
|
+
except (TypeError, ValueError):
|
|
201
|
+
minute_limit = self.max_minutes
|
|
202
|
+
if elapsed_minutes >= minute_limit:
|
|
203
|
+
return "max_minutes reached (%s)" % self.max_minutes
|
|
204
|
+
return None
|
|
205
|
+
|
|
206
|
+
def note_call(self):
|
|
207
|
+
"""Record one completed engine call."""
|
|
208
|
+
self.calls_made += 1
|
radarhound/calllog.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
"""Call log: one JSON line per engine call in ``calls.jsonl`` (B1a)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import threading
|
|
7
|
+
from datetime import datetime, timezone
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
|
|
10
|
+
_LOCK = threading.Lock()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def record(
|
|
14
|
+
calls_file,
|
|
15
|
+
*,
|
|
16
|
+
engine,
|
|
17
|
+
model,
|
|
18
|
+
effort,
|
|
19
|
+
tools,
|
|
20
|
+
seconds,
|
|
21
|
+
rc,
|
|
22
|
+
task_chars,
|
|
23
|
+
answer_chars,
|
|
24
|
+
review_id,
|
|
25
|
+
pass_name,
|
|
26
|
+
stage=None,
|
|
27
|
+
usage=None,
|
|
28
|
+
):
|
|
29
|
+
"""Append one JSON line for an engine call. Returns the entry dict.
|
|
30
|
+
|
|
31
|
+
``usage`` is the :class:`EngineResult` usage dict (``input``,
|
|
32
|
+
``output``, ``cache_read``, ``cache_write``, ``cost_usd``, any may
|
|
33
|
+
be absent); when a dict, the present keys are stored as
|
|
34
|
+
``in_tokens``, ``out_tokens``, ``cache_read_tokens``,
|
|
35
|
+
``cache_write_tokens``, ``cost_usd``. With None the entry keys are
|
|
36
|
+
exactly today's.
|
|
37
|
+
"""
|
|
38
|
+
entry = {
|
|
39
|
+
"ts": datetime.now(timezone.utc).isoformat(),
|
|
40
|
+
"engine": engine,
|
|
41
|
+
"model": model,
|
|
42
|
+
"effort": effort,
|
|
43
|
+
"tools": tools,
|
|
44
|
+
"seconds": seconds,
|
|
45
|
+
"rc": rc,
|
|
46
|
+
"task_chars": task_chars,
|
|
47
|
+
"answer_chars": answer_chars,
|
|
48
|
+
"review_id": review_id,
|
|
49
|
+
"pass": pass_name,
|
|
50
|
+
}
|
|
51
|
+
if stage is not None:
|
|
52
|
+
entry["stage"] = stage
|
|
53
|
+
if isinstance(usage, dict):
|
|
54
|
+
if "input" in usage:
|
|
55
|
+
entry["in_tokens"] = usage["input"]
|
|
56
|
+
if "output" in usage:
|
|
57
|
+
entry["out_tokens"] = usage["output"]
|
|
58
|
+
if "cache_read" in usage:
|
|
59
|
+
entry["cache_read_tokens"] = usage["cache_read"]
|
|
60
|
+
if "cache_write" in usage:
|
|
61
|
+
entry["cache_write_tokens"] = usage["cache_write"]
|
|
62
|
+
if "cost_usd" in usage:
|
|
63
|
+
entry["cost_usd"] = usage["cost_usd"]
|
|
64
|
+
path = Path(calls_file)
|
|
65
|
+
if path.parent and str(path.parent) not in ("", "."):
|
|
66
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
67
|
+
with _LOCK:
|
|
68
|
+
with open(path, "a", encoding="utf-8") as handle:
|
|
69
|
+
handle.write(json.dumps(entry) + "\n")
|
|
70
|
+
return entry
|