Skip to content

Commit 8582631

Browse files
committed
Ask AI: keep reports and diffs when the model is refused, and bound the clone
A report or a diff now comes back even when the model cannot be reached to write about it. A firewall in front of an AI service can refuse a request body with code in it, and that used to fail the whole question. The report falls back to the summary and the advice computed from the data, the diff is shown as it is, and the answer says why there is no write up. The clone behind a diff reads history back to a month before the finding, without file contents, and goes back a year only when that was not enough. A branch that has not moved since then is read one commit deep. Every diff in one question shares a 75 second budget, so a large repository cannot hold the request open longer than the load balancer will wait.
1 parent f25d06a commit 8582631

2 files changed

Lines changed: 81 additions & 27 deletions

File tree

‎app/core/ask.py‎

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -841,18 +841,32 @@ def call(sys_text, prompt, tokens):
841841
diffs = ask_diff.diffs(ids)
842842

843843
files_note = (f"\nFiles made: {', '.join(sorted(wants))}." if wants else "")
844+
# A report or a diff is worth having even when the model cannot be
845+
# reached to write about it: a firewall in front of the service may refuse
846+
# a body with code in it. The numbers and the diff come from the data, so
847+
# they are shown with a sentence saying why there is no write up.
844848
if report:
845849
from app.core import ask_report
846850

847-
answer = call(REPORT_SYSTEM,
848-
f"Conversation:\n{talk}\n\nReport data (JSON):\n"
849-
f"{json.dumps(ask_report.for_model(report), default=str)[:60_000]}",
850-
3000).strip()[:6000]
851+
try:
852+
answer = call(REPORT_SYSTEM,
853+
f"Conversation:\n{talk}\n\nReport data (JSON):\n"
854+
f"{json.dumps(ask_report.for_model(report), default=str)[:60_000]}",
855+
3000).strip()[:6000]
856+
except AskError as exc:
857+
answer = "\n".join(
858+
["Summary:", report.get("summary", ""), "", "What to do first:"]
859+
+ [f"- {r['priority']}: {r['title']}" for r in report.get("recommendations", [])]
860+
+ ["", f"(The model could not write this up: {exc} The numbers "
861+
"above and in the PDF come straight from the data.)"])
851862
elif diffs:
852-
answer = call(DIFF_SYSTEM,
853-
f"Conversation:\n{talk}\n\nDiffs (JSON):\n"
854-
f"{_diff_for_model(diffs, bool(cfg.get('ai.send_code', True)))}"
855-
f"{files_note}", 2000).strip()[:4000]
863+
try:
864+
answer = call(DIFF_SYSTEM,
865+
f"Conversation:\n{talk}\n\nDiffs (JSON):\n"
866+
f"{_diff_for_model(diffs, bool(cfg.get('ai.send_code', True)))}"
867+
f"{files_note}", 2000).strip()[:4000]
868+
except AskError as exc:
869+
answer = (f"The changes are below. The model could not explain them: {exc}")
856870
else:
857871
answer = call(ANSWER_SYSTEM,
858872
f"Conversation:\n{talk}\n\nQuery results (JSON):\n"

‎app/core/ask_diff.py‎

Lines changed: 59 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
scan that marked it fixed. That is the fix.
1212
open the file when it was first found, against the file now.
1313
14-
A blobless clone of the one branch, in memory where there is some, gone on
14+
A clone of the one branch's recent history, without file contents,, in memory where there is some, gone on
1515
the way out. Commit dates are read along the branch's own line of merges,
1616
so a change made on a side branch weeks earlier and merged in between the
1717
two scans still lands in the window.
@@ -27,14 +27,18 @@
2727
import re
2828
import subprocess
2929
import tempfile
30-
from datetime import datetime, timezone
30+
import time
31+
from datetime import datetime, timedelta, timezone
3132
from pathlib import Path
3233

3334
log = logging.getLogger("gcr.ask.diff")
3435

3536
MAX_DIFFS = 3
3637
MAX_LINES = 400
37-
GIT_TIMEOUT = 120
38+
GIT_TIMEOUT = 60
39+
# For every diff in one question together, so a large repository cannot hold
40+
# the request open past what the load balancer in front will wait for.
41+
TOTAL_SECONDS = 75
3842

3943
_BRANCH = re.compile(r"[A-Za-z0-9._/+-]{1,255}")
4044
_REPO = re.compile(r"[A-Za-z0-9._-]+(/[A-Za-z0-9._-]+)+")
@@ -61,8 +65,14 @@ def _utc(value):
6165
return value.astimezone(timezone.utc)
6266

6367

64-
def _git(args: list, cwd: Path, cred: list, timeout: int = GIT_TIMEOUT) -> tuple:
68+
def _git(args: list, cwd: Path, cred: list, timeout: int = GIT_TIMEOUT,
69+
deadline: float = 0) -> tuple:
6570
"""-> (ok, stdout, short error). Never raises, never echoes a credential."""
71+
if deadline:
72+
left = deadline - time.monotonic()
73+
if left < 2:
74+
return False, "", "out of time for this question"
75+
timeout = min(timeout, left)
6676
env = dict(os.environ, GIT_TERMINAL_PROMPT="0", GIT_ASKPASS="/bin/false")
6777
try:
6878
done = subprocess.run(["git", "-C", str(cwd)] + cred + args,
@@ -125,7 +135,7 @@ def load(finding_ids: list) -> list:
125135
return out
126136

127137

128-
def _one(item: dict, work: Path) -> None:
138+
def _one(item: dict, work: Path, deadline: float = 0) -> None:
129139
"""Fill item with diff, commits and window, or an error. In place."""
130140
from app.core.code_reasoning import mask
131141
from app.core.recheck import _credential_args
@@ -147,29 +157,55 @@ def _one(item: dict, work: Path) -> None:
147157
cred = _credential_args(token_file, item["provider"])
148158
dest = work / "repo"
149159
try:
160+
# History back to a month before the earlier moment, without file
161+
# contents. Enough for almost every finding, and bounded however old
162+
# and large the repository is. Deepened once if it was not enough.
163+
def since(days):
164+
return (item["before_at"] - timedelta(days=days)).strftime("%Y-%m-%d")
165+
166+
url = "%s/%s.git" % (item["web"], item["repository"])
150167
ok, _out, why = _git(["clone", "--quiet", "--filter=blob:none", "--no-checkout",
151168
"--single-branch", "--branch=" + item["branch"],
152-
"--no-tags", "--", "%s/%s.git" % (item["web"], item["repository"]),
153-
str(dest)], work, cred)
169+
"--no-tags", "--shallow-since=" + since(30), "--",
170+
url, str(dest)], work, cred, deadline=deadline)
171+
quiet = False
172+
if not ok:
173+
# A branch with no commits in that month refuses a date limited
174+
# clone. Then it has not moved since before the finding, which
175+
# one commit is enough to show.
176+
ok, _out, why = _git(["clone", "--quiet", "--filter=blob:none", "--no-checkout",
177+
"--single-branch", "--branch=" + item["branch"],
178+
"--no-tags", "--depth=1", "--", url, str(dest)],
179+
work, cred, deadline=deadline)
180+
quiet = ok
154181
if not ok:
155182
item["error"] = why or "The branch could not be fetched."
156183
return
157184

158185
def commit_before(when):
159186
stamp = when.strftime("%Y-%m-%dT%H:%M:%SZ")
160187
ok, out, _why = _git(["rev-list", "-1", "--first-parent",
161-
"--before=" + stamp, "HEAD"], dest, cred)
188+
"--before=" + stamp, "HEAD"], dest, cred, deadline=deadline)
162189
return out.strip() if ok else ""
163190

164-
before = commit_before(item["before_at"])
165-
after = commit_before(item["after_at"]) if item["after_at"] else ""
166-
if not item["after_at"]:
167-
ok, out, _why = _git(["rev-parse", "HEAD"], dest, cred)
168-
after = out.strip() if ok else ""
191+
if quiet:
192+
before = after = commit_before(item["before_at"])
193+
else:
194+
before = commit_before(item["before_at"])
195+
if not before:
196+
_git(["fetch", "--quiet", "--filter=blob:none", "--no-tags",
197+
"--shallow-since=" + since(400), "origin"], dest, cred,
198+
deadline=deadline)
199+
before = commit_before(item["before_at"])
200+
if item["after_at"]:
201+
after = commit_before(item["after_at"])
202+
else:
203+
ok, out, _why = _git(["rev-parse", "HEAD"], dest, cred, deadline=deadline)
204+
after = out.strip() if ok else ""
169205
if not before or not after:
170-
item["error"] = ("The branch has no commit from before %s, so there "
171-
"is nothing to compare against."
172-
% item["before_at"].strftime("%Y-%m-%d"))
206+
item["error"] = ("The branch has no commit from before %s within the "
207+
"last year of its history, so there is nothing to "
208+
"compare against." % item["before_at"].strftime("%Y-%m-%d"))
173209
return
174210
item["before_commit"], item["after_commit"] = before[:12], after[:12]
175211
if before == after:
@@ -179,10 +215,10 @@ def commit_before(when):
179215

180216
ok, log_out, _why = _git(["log", "--no-color", "--format=%h %ad %an: %s",
181217
"--date=short", "%s..%s" % (before, after),
182-
"--", item["file"]], dest, cred)
218+
"--", item["file"]], dest, cred, deadline=deadline)
183219
commits = [mask(line)[:200] for line in log_out.splitlines()[:20]] if ok else []
184220
ok, diff, why = _git(["diff", "--no-color", "--no-ext-diff", "--unified=5",
185-
before, after, "--", item["file"]], dest, cred)
221+
before, after, "--", item["file"]], dest, cred, deadline=deadline)
186222
if not ok:
187223
item["error"] = why or "The diff could not be read."
188224
return
@@ -216,14 +252,18 @@ def diffs(finding_ids: list) -> list:
216252
item.setdefault("error", "")
217253
item["error"] = item["error"] or "The server is busy reading code. Ask again shortly."
218254
return [_public(i) for i in items]
255+
deadline = time.monotonic() + TOTAL_SECONDS
219256
try:
220257
for item in items:
221258
if item["error"]:
222259
continue
260+
if time.monotonic() > deadline - 5:
261+
item["error"] = "Out of time for this question. Ask about this one on its own."
262+
continue
223263
with tempfile.TemporaryDirectory(prefix="gcr-diff-",
224264
dir=memory_dir() or None) as tmp:
225265
try:
226-
_one(item, Path(tmp))
266+
_one(item, Path(tmp), deadline)
227267
except Exception: # noqa: BLE001 - one bad repo is not the answer
228268
log.exception("diff for finding %s failed", item["finding_id"])
229269
item["error"] = "The diff could not be made."

0 commit comments

Comments
 (0)