Skip to content

Commit fbb0402

Browse files
author
Peter Steinberger
committed
fix: harden bounded review hydration and issue retry recovery
1 parent 2817b60 commit fbb0402

7 files changed

Lines changed: 665 additions & 27 deletions

‎src/clawsweeper-review-blobs.ts‎

Lines changed: 128 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { spawnSync } from "node:child_process";
22

33
const MAX_REVIEW_FILES = 80;
44
const MAX_GIT_OUTPUT_BYTES = 4 * 1024 * 1024;
5+
const MAX_REVIEW_BLOB_BYTES = 4 * 1024 * 1024;
56
const GIT_OBJECT_ID = /^[0-9a-f]{40,64}$/i;
67

78
type ReviewBlobFile = {
@@ -20,11 +21,13 @@ export function hydratePullRequestReviewBlobs({
2021
baseSha,
2122
headSha,
2223
files,
24+
resolveBlobSizes,
2325
}: {
2426
targetDir: string;
2527
baseSha: string;
2628
headSha: string;
2729
files: readonly unknown[];
30+
resolveBlobSizes?: (objectIds: readonly string[]) => ReadonlyMap<string, number>;
2831
}): ReviewBlobHydration {
2932
if (
3033
!GIT_OBJECT_ID.test(baseSha) ||
@@ -73,25 +76,134 @@ export function hydratePullRequestReviewBlobs({
7376
}
7477

7578
if (objectIds.size === 0) return { hydrated: true, blobs: 0 };
76-
const hydrated = spawnSync("git", ["cat-file", "--batch-check=%(objectname) %(objecttype)"], {
77-
cwd: targetDir,
78-
encoding: "utf8",
79-
env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
80-
input: `${[...objectIds].join("\n")}\n`,
81-
maxBuffer: MAX_GIT_OUTPUT_BYTES,
82-
});
83-
if (hydrated.error || hydrated.status !== 0) return { hydrated: false, blobs: 0 };
84-
const received = hydrated.stdout.trim().split("\n");
79+
const objectInput = `${[...objectIds].join("\n")}\n`;
80+
const localObjects = spawnSync(
81+
"git",
82+
["cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)"],
83+
{
84+
cwd: targetDir,
85+
encoding: "utf8",
86+
env: { ...process.env, GIT_OPTIONAL_LOCKS: "0", GIT_NO_LAZY_FETCH: "1" },
87+
input: objectInput,
88+
maxBuffer: MAX_GIT_OUTPUT_BYTES,
89+
},
90+
);
91+
if (localObjects.error || localObjects.status !== 0) return { hydrated: false, blobs: 0 };
92+
const found = localObjects.stdout.trim().split("\n");
93+
if (found.length !== objectIds.size) return { hydrated: false, blobs: 0 };
94+
const sizes = new Map<string, number>();
95+
const missing = new Set<string>();
96+
for (const entry of found) {
97+
const [objectId, type, size] = entry.split(" ");
98+
if (!objectId || !objectIds.has(objectId) || (type !== "blob" && type !== "missing")) {
99+
return { hydrated: false, blobs: 0 };
100+
}
101+
if (type === "missing") missing.add(objectId);
102+
else sizes.set(objectId, Number(size));
103+
}
104+
if (missing.size > 0) {
105+
if (!resolveBlobSizes) return { hydrated: false, blobs: 0 };
106+
let remoteSizes: ReadonlyMap<string, number>;
107+
try {
108+
remoteSizes = resolveBlobSizes([...missing]);
109+
} catch {
110+
return { hydrated: false, blobs: 0 };
111+
}
112+
for (const objectId of missing) {
113+
const bytes = remoteSizes.get(objectId);
114+
if (bytes === undefined) return { hydrated: false, blobs: 0 };
115+
sizes.set(objectId, bytes);
116+
}
117+
}
118+
119+
let objectBytes = 0;
120+
let skippedOversizedBlob = false;
121+
const bounded = new Set<string>();
122+
for (const objectId of objectIds) {
123+
const bytes = sizes.get(objectId);
124+
if (
125+
bytes === undefined ||
126+
!Number.isSafeInteger(bytes) ||
127+
bytes < 0 ||
128+
bytes > MAX_REVIEW_BLOB_BYTES - objectBytes
129+
) {
130+
skippedOversizedBlob = true;
131+
continue;
132+
}
133+
bounded.add(objectId);
134+
objectBytes += bytes;
135+
}
136+
137+
const boundedMissing = [...missing].filter((objectId) => bounded.has(objectId));
138+
if (boundedMissing.length > 0) {
139+
const fetched = spawnSync(
140+
"git",
141+
[
142+
"-c",
143+
"fetch.negotiationAlgorithm=noop",
144+
"fetch",
145+
"origin",
146+
"--no-tags",
147+
"--no-write-fetch-head",
148+
"--recurse-submodules=no",
149+
"--filter=blob:none",
150+
"--stdin",
151+
],
152+
{
153+
cwd: targetDir,
154+
encoding: "utf8",
155+
env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
156+
input: `${boundedMissing.join("\n")}\n`,
157+
maxBuffer: MAX_GIT_OUTPUT_BYTES,
158+
},
159+
);
160+
if (fetched.error || fetched.status !== 0) return { hydrated: false, blobs: 0 };
161+
}
162+
return { hydrated: !skippedOversizedBlob, blobs: bounded.size };
163+
}
164+
165+
export function githubReviewBlobSizes({
166+
repository,
167+
objectIds,
168+
request,
169+
}: {
170+
repository: string;
171+
objectIds: readonly string[];
172+
request: (query: string) => unknown;
173+
}): ReadonlyMap<string, number> {
174+
const match = repository.match(/^([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)$/);
85175
if (
86-
received.length !== objectIds.size ||
87-
received.some((entry) => {
88-
const [objectId, type] = entry.split(" ");
89-
return !objectId || !objectIds.has(objectId) || type !== "blob";
90-
})
176+
!match ||
177+
match[1] === "." ||
178+
match[1] === ".." ||
179+
match[2] === "." ||
180+
match[2] === ".." ||
181+
objectIds.length > MAX_REVIEW_FILES * 2
91182
) {
92-
return { hydrated: false, blobs: 0 };
183+
throw new Error("invalid bounded review blob metadata request");
184+
}
185+
const objects = objectIds.map((objectId, index) => {
186+
if (!GIT_OBJECT_ID.test(objectId)) throw new Error("invalid review blob object ID");
187+
return `b${index}: object(oid: "${objectId}") { ... on Blob { byteSize } }`;
188+
});
189+
const query = `query { repository(owner: "${match[1]}", name: "${match[2]}") { ${objects.join(" ")} } }`;
190+
const response = request(query);
191+
if (!response || typeof response !== "object") throw new Error("invalid review blob response");
192+
const data = (response as { data?: unknown }).data;
193+
if (!data || typeof data !== "object") throw new Error("missing review blob response data");
194+
const values = (data as { repository?: unknown }).repository;
195+
if (!values || typeof values !== "object") throw new Error("missing review blob repository");
196+
const result = new Map<string, number>();
197+
for (const [index, objectId] of objectIds.entries()) {
198+
const object = (values as Record<string, unknown>)[`b${index}`];
199+
const bytes =
200+
object && typeof object === "object" ? (object as { byteSize?: unknown }).byteSize : null;
201+
if (typeof bytes !== "number" || !Number.isSafeInteger(bytes) || bytes < 0) {
202+
throw new Error("invalid review blob size");
203+
}
204+
result.set(objectId, bytes);
93205
}
94-
return { hydrated: true, blobs: objectIds.size };
206+
return result;
95207
}
96208

97209
function safeReviewPath(value: unknown): string | null {

‎src/clawsweeper.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,10 @@ import {
5555
import { parseGhJson, parseGhJsonLinesWithRetry, parseGhJsonWithRetry } from "./github-json.js";
5656
import { stableJson } from "./stable-json.js";
5757
import { reviewPullChecksDigestParts } from "./review-checks-digest.js";
58-
import { hydratePullRequestReviewBlobs } from "./clawsweeper-review-blobs.js";
58+
import {
59+
githubReviewBlobSizes,
60+
hydratePullRequestReviewBlobs,
61+
} from "./clawsweeper-review-blobs.js";
5962
import { coverageTrackedItemIdsFromManifest } from "./review-coverage-manifest.js";
6063
import {
6164
LEGACY_FIXED_CLOSE_SKIP_ACTIONS,
@@ -4610,6 +4613,12 @@ function semanticPullFilesWithTreeIdentity(options: {
46104613
baseSha,
46114614
headSha,
46124615
files: options.files,
4616+
resolveBlobSizes: (objectIds) =>
4617+
githubReviewBlobSizes({
4618+
repository: targetRepo(),
4619+
objectIds,
4620+
request: (query) => ghJson(["api", "graphql", "-f", `query=${query}`]),
4621+
}),
46134622
});
46144623
if (!hydration.hydrated) {
46154624
console.warn("pull-request review blobs could not be hydrated before restricted review");

‎src/repair/issue-implementation-intake.ts‎

Lines changed: 77 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,13 @@ type ReviewReport = {
5454
};
5555

5656
const args = parseArgs(process.argv.slice(2));
57+
const OPEN_IMPLEMENTATION_PR_BLOCKERS = [
58+
"existing ClawSweeper issue implementation PR is open",
59+
"open PR already mentions this issue",
60+
"open PR already covers a related issue in this work cluster",
61+
"review report references an open or unverifiable pull request",
62+
];
63+
const ISSUE_IMPLEMENTATION_BLOCKER_RECHECK_DELAY_MS = 30 * 60_000;
5764

5865
function main() {
5966
const command = String(args._[0] ?? "prepare");
@@ -130,6 +137,17 @@ function prepare() {
130137
: null;
131138
let workerDispatched = previousAudit?.frontmatter.worker_dispatched === "true";
132139
let workerAttemptCount = issueImplementationWorkerAttemptCount(previousAudit);
140+
if (
141+
authoritativeReviewOrdering({
142+
audit: previousAudit,
143+
report,
144+
reportRevision: reportRevisionSha256(reportMarkdown),
145+
}) < 0
146+
) {
147+
die(
148+
"local issue review is older than the authoritative intake; refresh records before retrying",
149+
);
150+
}
133151
if (decision.shouldRepair && existingJob && !operatorOverride) {
134152
if (!issueImplementationJobNeedsRefresh(previousAudit, reportMarkdown)) {
135153
recoverExistingJob = intakeAuditAwaitsWorkerDispatch(previousAudit);
@@ -169,12 +187,15 @@ function prepare() {
169187
const jobReportRevisionSha256 = decision.shouldRepair
170188
? reportRevisionSha256(reportMarkdown)
171189
: existingIssueImplementationJobRevision(previousAudit);
190+
const blockedByOpenImplementationPr = decision.blockers.some((blocker) =>
191+
OPEN_IMPLEMENTATION_PR_BLOCKERS.includes(blocker),
192+
);
172193
const workerRetryAfter =
173194
existingJob &&
174195
!decision.shouldRepair &&
175196
decision.status !== "already_queued" &&
176-
!workerDispatched
177-
? new Date(Date.now() + 30 * 60_000).toISOString()
197+
(!workerDispatched || blockedByOpenImplementationPr)
198+
? new Date(Date.now() + ISSUE_IMPLEMENTATION_BLOCKER_RECHECK_DELAY_MS).toISOString()
178199
: workerDispatched
179200
? nextIssueImplementationWorkerRetry()
180201
: "";
@@ -335,9 +356,10 @@ export function discoverImplementationCandidates({
335356
}
336357
const candidates: { candidate: LooseRecord; existingJob: boolean; retryDue: boolean }[] = [];
337358
for (const { markdown, number, reportPath, repository } of reviewsByIssue.values()) {
359+
const parsedReport = parseReviewReport(markdown);
338360
const decision = reportOnlyDecision({
339361
targetRepo,
340-
report: parseReviewReport(markdown),
362+
report: parsedReport,
341363
reportMarkdown: markdown,
342364
candidateKind,
343365
});
@@ -347,14 +369,32 @@ export function discoverImplementationCandidates({
347369
const previousAudit = existingJob
348370
? intakeAudit({ root: jobRoot, repo: repository, number })
349371
: null;
372+
const reportRevision = reportRevisionSha256(markdown);
373+
const reviewOrdering = authoritativeReviewOrdering({
374+
audit: previousAudit,
375+
report: parsedReport,
376+
reportRevision,
377+
});
378+
const newerReview = reviewOrdering > 0;
379+
const blockedByOpenImplementationPr =
380+
previousAudit?.frontmatter.decision === "not_eligible" &&
381+
previousAudit.frontmatter.worker_dispatched === "true" &&
382+
OPEN_IMPLEMENTATION_PR_BLOCKERS.some((blocker) => previousAudit.body.includes(blocker));
383+
const blockerRecheckDue =
384+
blockedByOpenImplementationPr &&
385+
(!Number.isFinite(Date.parse(previousAudit?.frontmatter.worker_retry_after ?? "")) ||
386+
intakeAuditRetryDue(previousAudit));
350387
if (existingJob) {
388+
if (reviewOrdering < 0) continue;
351389
if (intakeAuditRetryDeferred(previousAudit, markdown)) continue;
352390
if (
391+
!newerReview &&
392+
!blockerRecheckDue &&
353393
!intakeAuditAwaitsWorkerDispatch(previousAudit) &&
354394
!issueImplementationJobNeedsRefresh(previousAudit, markdown) &&
355395
!dispatchedIssueImplementationWorkerRetryDue({
356396
audit: previousAudit,
357-
reportRevision: reportRevisionSha256(markdown),
397+
reportRevision,
358398
})
359399
) {
360400
continue;
@@ -367,6 +407,8 @@ export function discoverImplementationCandidates({
367407
candidates.push({
368408
existingJob,
369409
retryDue:
410+
newerReview ||
411+
blockerRecheckDue ||
370412
intakeAuditRetryDue(previousAudit) ||
371413
(intakeAuditAwaitsWorkerDispatch(previousAudit) &&
372414
!Number.isFinite(Date.parse(previousAudit?.frontmatter.worker_retry_after ?? ""))),
@@ -402,6 +444,34 @@ function reviewFreshness(report: ReviewReport): readonly [number, number] {
402444
];
403445
}
404446

447+
function authoritativeReviewOrdering({
448+
audit,
449+
report,
450+
reportRevision,
451+
}: {
452+
audit: ReviewReport | null;
453+
report: ReviewReport;
454+
reportRevision: string;
455+
}) {
456+
if (!audit || audit.frontmatter.report_revision_sha256 === reportRevision) return 0;
457+
const incoming = reviewFreshness(report);
458+
const audited = [
459+
Date.parse(audit.frontmatter.report_item_updated_at ?? ""),
460+
Date.parse(audit.frontmatter.report_reviewed_at ?? ""),
461+
].map((value) => (Number.isFinite(value) ? value : Number.NEGATIVE_INFINITY));
462+
if (audited.some(Number.isFinite)) {
463+
for (const [index, incomingValue] of incoming.entries()) {
464+
const auditedValue = audited[index] ?? Number.NEGATIVE_INFINITY;
465+
if (!Number.isFinite(incomingValue) || !Number.isFinite(auditedValue)) continue;
466+
if (incomingValue !== auditedValue) return incomingValue > auditedValue ? 1 : -1;
467+
}
468+
return 0;
469+
}
470+
const preparedAt = Date.parse(audit.frontmatter.prepared_at ?? "");
471+
if (!Number.isFinite(incoming[1]) || !Number.isFinite(preparedAt)) return 0;
472+
return incoming[1] > preparedAt ? 1 : -1;
473+
}
474+
405475
function compareReviewFreshness(left: readonly number[], right: readonly number[]) {
406476
for (const [index, timestamp] of left.entries()) {
407477
if (timestamp > (right[index] ?? Number.NEGATIVE_INFINITY)) return 1;
@@ -829,12 +899,15 @@ function writeAudit(context: LooseRecord) {
829899
const jobLine = context.decision.shouldRepair
830900
? `- Job: \`${relative(context.jobPath)}\``
831901
: "- Job: none";
902+
const [itemUpdatedAt, reviewedAt] = reviewFreshness(context.report as ReviewReport);
832903
const body = `---
833904
repo: ${context.targetRepo}
834905
number: ${context.itemNumber}
835906
report_repo: ${context.reportRepo}
836907
report_path: ${context.reportPath}
837908
report_revision_sha256: ${reportRevisionSha256(context.reportMarkdown)}
909+
report_item_updated_at: ${Number.isFinite(itemUpdatedAt) ? new Date(itemUpdatedAt).toISOString() : ""}
910+
report_reviewed_at: ${Number.isFinite(reviewedAt) ? new Date(reviewedAt).toISOString() : ""}
838911
job_report_revision_sha256: ${context.jobReportRevisionSha256 || ""}
839912
decision: ${context.decision.status}
840913
prepared_at: ${context.preparedAt}

‎src/repair/issue-worker-recovery.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ export function dispatchedIssueImplementationWorkerRetryDue({
4242
) {
4343
return false;
4444
}
45+
if (!sameReview) return true;
4546
const retryAfter = Date.parse(String(audit.frontmatter.worker_retry_after ?? ""));
4647
if (Number.isFinite(retryAfter)) return retryAfter <= nowMs;
4748
const preparedAt = Date.parse(String(audit.frontmatter.prepared_at ?? ""));

0 commit comments

Comments
 (0)