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
1515the way out. Commit dates are read along the branch's own line of merges,
1616so a change made on a side branch weeks earlier and merged in between the
1717two scans still lands in the window.
2727import re
2828import subprocess
2929import tempfile
30- from datetime import datetime , timezone
30+ import time
31+ from datetime import datetime , timedelta , timezone
3132from pathlib import Path
3233
3334log = logging .getLogger ("gcr.ask.diff" )
3435
3536MAX_DIFFS = 3
3637MAX_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