Skip to content

Commit 5bfa2d9

Browse files
authored
perf(apply): memoize per-item guard reads; stabilize coalescing race test (#1060)
* perf(apply): memoize per-item guard reads * test(queue): make coalescing race order-agnostic * docs: remove release-owned changelog entry
1 parent f6f6bfc commit 5bfa2d9

6 files changed

Lines changed: 242 additions & 8 deletions

‎src/clawsweeper-apply-decision-workflow.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ export function createApplyDecisionWorkflow(dependencies: CreateApplyDecisionWor
139139
recordApplyActionEvents,
140140
recordApplyActionLedgerItemResults,
141141
recordApplyMutationBoundary,
142+
resetGuardReadCache,
142143
removeCurrentCursorTraceItem,
143144
removeIssueLabel,
144145
renderReviewCommentFromReport,
@@ -452,6 +453,7 @@ export function createApplyDecisionWorkflow(dependencies: CreateApplyDecisionWor
452453
// oxfmt-ignore
453454
for (const entry of fileEntries) {
454455
releaseActiveApplyMutationLease();
456+
resetGuardReadCache();
455457
const file = entry.name;
456458
const path = entry.path;
457459
if (runtimeBudgetExceeded(startedAtMs, maxRuntimeMs, Date.now())) {
@@ -473,6 +475,7 @@ export function createApplyDecisionWorkflow(dependencies: CreateApplyDecisionWor
473475
try {
474476
const markMutationObserved = (): void => {
475477
if (dryRun) return;
478+
resetGuardReadCache();
476479
activeApplyItem = { repo, number, mutationOccurred: true };
477480
mutationByItem.set(`${repo}#${number}`, true);
478481
};

‎src/clawsweeper-apply-dependencies.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -360,6 +360,7 @@ export interface CreateApplyDecisionWorkflowDependencies {
360360
reportRealBehaviorProof: (markdown: string) => RealBehaviorProof;
361361
reportSecurityReview: (markdown: string) => SecurityReview;
362362
reportTelegramVisibleProof: (markdown: string) => TelegramVisibleProof;
363+
resetGuardReadCache: () => void;
363364
reviewCommentBodyDigest: (body: string) => string;
364365
reviewCommentHasCloseVerdictForCanonical: (
365366
comment: Record<string, unknown> | undefined,

‎src/clawsweeper-apply-guards.ts‎

Lines changed: 42 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,48 @@ import { createApplyGuardProof } from "./clawsweeper-apply-guard-proof.js";
55
import { createApplyGuardCapacity } from "./clawsweeper-apply-guard-capacity.js";
66
export { STALLED_UNPROVEN_PROOF_STATUSES } from "./clawsweeper-apply-guard-dependencies.js";
77

8+
type GuardReadCacheEntry = { ok: true; value: unknown } | { ok: false; error: unknown };
9+
810
export function createApplyGuards(dependencies: ApplyGuardDependencies) {
9-
const activity = createApplyGuardActivity({ ...dependencies });
10-
const policy = createApplyGuardPolicy({ ...dependencies, ...activity });
11-
const proof = createApplyGuardProof({ ...dependencies, ...activity, ...policy });
12-
const capacity = createApplyGuardCapacity({ ...dependencies, ...activity, ...policy, ...proof });
11+
const guardReadCache = new Map<string, GuardReadCacheEntry>();
12+
13+
function memoizedGuardRead<T>(kind: "json" | "paged", args: readonly string[], read: () => T): T {
14+
const key = JSON.stringify([kind, ...args]);
15+
const cached = guardReadCache.get(key);
16+
if (cached) {
17+
if (cached.ok) return cached.value as T;
18+
throw cached.error;
19+
}
20+
try {
21+
const value = read();
22+
guardReadCache.set(key, { ok: true, value });
23+
return value;
24+
} catch (error) {
25+
guardReadCache.set(key, { ok: false, error });
26+
throw error;
27+
}
28+
}
29+
30+
const guardDependencies: ApplyGuardDependencies = {
31+
...dependencies,
32+
ghJson: <T>(args: string[]): T =>
33+
memoizedGuardRead("json", args, () => dependencies.ghJson<T>(args)),
34+
ghPaged: <T>(path: string): T[] =>
35+
memoizedGuardRead("paged", [path], () => dependencies.ghPaged<T>(path)),
36+
};
37+
const activity = createApplyGuardActivity({ ...guardDependencies });
38+
const policy = createApplyGuardPolicy({ ...guardDependencies, ...activity });
39+
const proof = createApplyGuardProof({ ...guardDependencies, ...activity, ...policy });
40+
const capacity = createApplyGuardCapacity({
41+
...guardDependencies,
42+
...activity,
43+
...policy,
44+
...proof,
45+
});
46+
47+
function resetGuardReadCache(): void {
48+
guardReadCache.clear();
49+
}
1350
const {
1451
abandonedPrAgeSkipReason,
1552
abandonedPrApplyBlockReasonSafe,
@@ -45,6 +82,7 @@ export function createApplyGuards(dependencies: ApplyGuardDependencies) {
4582
prAutoCloseExemptDecisionReason,
4683
prAutoCloseExemptLabel,
4784
pullRequestHeadActivity,
85+
resetGuardReadCache,
4886
staleVersionBugApplyBlockReasonSafe,
4987
stalledUnprovenPrAgeSkipReason,
5088
stalledUnprovenPrApplyBlockReasonSafe,

‎src/clawsweeper-runtime.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -536,12 +536,18 @@ const applyGuards = createApplyGuards({
536536
unsponsoredFeatureAgeSkipReason,
537537
unsponsoredFeatureCloseEnabled: () => unsponsoredFeatureCloseEnabled(),
538538
});
539+
const { resetGuardReadCache } = applyGuards;
539540
export const {
540541
abandonedPrAgeSkipReason,
541542
issueRecentHumanCommentBlockReasonFromComments,
542543
stalledUnprovenPrAgeSkipReason,
543-
stalledUnprovenProofRequestBlockReason,
544544
} = applyGuards;
545+
export function stalledUnprovenProofRequestBlockReason(
546+
...args: Parameters<typeof applyGuards.stalledUnprovenProofRequestBlockReason>
547+
): ReturnType<typeof applyGuards.stalledUnprovenProofRequestBlockReason> {
548+
resetGuardReadCache();
549+
return applyGuards.stalledUnprovenProofRequestBlockReason(...args);
550+
}
545551
const { prAutoCloseExemptDecisionReason, prAutoCloseExemptLabel } = applyGuards;
546552

547553
const contextHydration = createContextHydration({
Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,175 @@
1+
import assert from "node:assert/strict";
2+
import test from "node:test";
3+
4+
import { createApplyGuards } from "../dist/clawsweeper-apply-guards.js";
5+
6+
function asRecord(value) {
7+
return value && typeof value === "object" && !Array.isArray(value) ? value : {};
8+
}
9+
10+
function createGuards({ ghJson = () => ({}), ghPaged = () => [] } = {}) {
11+
return createApplyGuards({
12+
asRecord,
13+
authorPrBudget: () => 10,
14+
authorPrBudgetAgeSkipReason: () => null,
15+
authorPrBudgetCloseEnabled: () => true,
16+
ghJson,
17+
ghPaged,
18+
isMaintainerAuthorAssociation: (value) => ["MEMBER", "OWNER", "COLLABORATOR"].includes(value),
19+
isMaintainerAuthored: () => false,
20+
isOlderThanDays: () => true,
21+
labelNames: (value) =>
22+
Array.isArray(value)
23+
? value.flatMap((label) => {
24+
if (typeof label === "string") return [label];
25+
const name = asRecord(label).name;
26+
return typeof name === "string" ? [name] : [];
27+
})
28+
: [],
29+
login: (value) => {
30+
const login = asRecord(value).login;
31+
return typeof login === "string" ? login : undefined;
32+
},
33+
normalizeLabelName: (label) => label.trim().toLowerCase(),
34+
obsoleteFixPrAgeSkipReason: () => null,
35+
obsoleteFixPrCloseEnabled: () => true,
36+
protectedLabels: () => [],
37+
quoteGitHubSearchTerm: (term) => term,
38+
reportPrRating: () => ({
39+
proofTier: "F",
40+
patchTier: "F",
41+
overallTier: "F",
42+
summary: "",
43+
nextSteps: [],
44+
}),
45+
reportRealBehaviorProof: () => ({
46+
status: "missing",
47+
summary: "",
48+
evidenceKind: "not_applicable",
49+
needsContributorAction: true,
50+
}),
51+
staleVersionBugAgeSkipReason: () => null,
52+
staleVersionBugCloseEnabled: () => true,
53+
stringOrUndefined: (value) => (typeof value === "string" ? value : undefined),
54+
targetRepo: () => "openclaw/openclaw",
55+
unconfirmedProductDirectionAgeSkipReason: () => null,
56+
unconfirmedProductDirectionCloseEnabled: () => true,
57+
unsponsoredFeatureAgeSkipReason: () => null,
58+
unsponsoredFeatureCloseEnabled: () => true,
59+
});
60+
}
61+
62+
test("apply guard reads share a paged endpoint across guard functions", () => {
63+
const calls = [];
64+
const guards = createGuards({
65+
ghPaged: (path) => {
66+
calls.push(path);
67+
return [];
68+
},
69+
});
70+
71+
guards.issueRecentHumanCommentBlockReasonSafe(42, 30);
72+
guards.stalledUnprovenProofRequestBlockReason(42);
73+
74+
assert.equal(
75+
calls.filter((path) => path === "repos/openclaw/openclaw/issues/42/comments").length,
76+
1,
77+
);
78+
assert.equal(
79+
calls.filter((path) => path === "repos/openclaw/openclaw/issues/42/timeline").length,
80+
1,
81+
);
82+
});
83+
84+
test("apply guard reads share a JSON endpoint across guard functions", () => {
85+
const calls = [];
86+
const guards = createGuards({
87+
ghJson: (args) => {
88+
calls.push(args);
89+
return {
90+
state: "open",
91+
created_at: "2025-01-01T00:00:00Z",
92+
labels: [],
93+
assignees: [],
94+
milestone: null,
95+
reactions: { total_count: 0 },
96+
};
97+
},
98+
});
99+
const item = { createdAt: "2025-01-01T00:00:00Z" };
100+
101+
guards.unsponsoredFeatureApplyBlockReasonSafe(42, item);
102+
guards.staleVersionBugApplyBlockReasonSafe(42, item);
103+
104+
assert.equal(
105+
calls.filter(
106+
(args) =>
107+
JSON.stringify(args) === JSON.stringify(["api", "repos/openclaw/openclaw/issues/42"]),
108+
).length,
109+
1,
110+
);
111+
});
112+
113+
test("apply guard read cache resets between items", () => {
114+
const calls = [];
115+
const guards = createGuards({
116+
ghPaged: (path) => {
117+
calls.push(path);
118+
return [];
119+
},
120+
});
121+
122+
guards.issueRecentHumanCommentBlockReasonSafe(1, 30);
123+
guards.issueRecentHumanCommentBlockReasonSafe(1, 30);
124+
assert.equal(calls.length, 1);
125+
126+
guards.resetGuardReadCache();
127+
guards.issueRecentHumanCommentBlockReasonSafe(1, 30);
128+
guards.issueRecentHumanCommentBlockReasonSafe(2, 30);
129+
130+
assert.deepEqual(calls, [
131+
"repos/openclaw/openclaw/issues/1/comments",
132+
"repos/openclaw/openclaw/issues/1/comments",
133+
"repos/openclaw/openclaw/issues/2/comments",
134+
]);
135+
});
136+
137+
test("apply guard read cache distinguishes full request arguments", () => {
138+
const calls = [];
139+
const guards = createGuards({
140+
ghJson: (args) => {
141+
calls.push(args);
142+
const path = args[1];
143+
if (path?.endsWith("/issues/42")) return { assignees: [] };
144+
if (path?.endsWith("/pulls/42")) {
145+
return args.includes("--jq")
146+
? { requested_reviewers: [], requested_teams: [] }
147+
: {
148+
created_at: "2025-01-01T00:00:00Z",
149+
mergeable: false,
150+
mergeable_state: "dirty",
151+
requested_reviewers: [],
152+
requested_teams: [],
153+
user: { login: "contributor" },
154+
head: {},
155+
};
156+
}
157+
return {};
158+
},
159+
});
160+
const item = { createdAt: "2025-01-01T00:00:00Z", labels: [] };
161+
162+
guards.unconfirmedProductDirectionApplyBlockReasonSafe(42, item, undefined, undefined);
163+
guards.lowSignalUnmergeablePrApplyBlockReasonSafe(42, 30);
164+
165+
const pullCalls = calls.filter((args) => args[1] === "repos/openclaw/openclaw/pulls/42");
166+
assert.equal(pullCalls.length, 2);
167+
assert.equal(
168+
pullCalls.some((args) => args.includes("--jq")),
169+
true,
170+
);
171+
assert.equal(
172+
pullCalls.some((args) => !args.includes("--jq")),
173+
true,
174+
);
175+
});

‎test/dashboard-worker.test.ts‎

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1162,9 +1162,20 @@ test("exact-review queue durably coalesces concurrent unchanged pull request edi
11621162
}
11631163
>;
11641164
};
1165-
assert.equal(state.items["Steipete/Nameplate#750"].revision, 1);
1166-
assert.equal(state.items["Steipete/Nameplate#750"].decision.sourceAuthoritySeq, 1);
1167-
assert.deepEqual(state.items["Steipete/Nameplate#750"].sourceAuthorityWatermark, {
1165+
// Either concurrent delivery may win the enqueue race; the stored item keeps
1166+
// the winner's repo casing (seq 1 sent "Steipete/Nameplate", seq 2 lowercase)
1167+
// while the loser dedupes case-insensitively and the watermark ends at the
1168+
// maximum sequence in both orders.
1169+
const queued = responses.find((response) => response.queued === true);
1170+
const storedKeys = Object.keys(state.items).filter(
1171+
(key) => key.toLowerCase() === "steipete/nameplate#750",
1172+
);
1173+
assert.deepEqual(storedKeys, [queued?.item_key]);
1174+
const item = state.items[storedKeys[0]];
1175+
const winnerAuthoritySeq = storedKeys[0] === "Steipete/Nameplate#750" ? 1 : 2;
1176+
assert.equal(item.revision, 1);
1177+
assert.equal(item.decision.sourceAuthoritySeq, winnerAuthoritySeq);
1178+
assert.deepEqual(item.sourceAuthorityWatermark, {
11681179
sequence: 2,
11691180
updatedAt: "2026-07-25T09:00:00Z",
11701181
});

0 commit comments

Comments
 (0)