Skip to content

Commit 4a39cfc

Browse files
steipetePeter Steinberger
andauthored
refactor: simplify sweep runtime and recover publication backlog (#1012)
* refactor: simplify sweep runtime and recover publication backlog * fix: fence non-atomic dead-letter cleanup * fix: preserve reconciliation counters across retries --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 8cdf2a1 commit 4a39cfc

22 files changed

Lines changed: 5507 additions & 4538 deletions

‎dashboard/wrangler.toml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,9 @@ EXACT_REVIEW_PUBLICATION_FRESH_LANE_ENABLED = "1"
9191
EXACT_REVIEW_PUBLICATION_FRESH_LANE_MAX_ITEMS = "2"
9292
EXACT_REVIEW_PUBLICATION_FRESH_LANE_MAX_AGE_MS = "900000"
9393
EXACT_REVIEW_PUBLICATION_BATCH_WAIT_MS = "60000"
94-
EXACT_REVIEW_PUBLICATION_BATCH_DISPATCH_COOLDOWN_MS = "30000"
94+
# Refill the existing eight bounded publisher slots quickly; a 30s refill
95+
# serialized batches despite dozens of ready publication records.
96+
EXACT_REVIEW_PUBLICATION_BATCH_DISPATCH_COOLDOWN_MS = "5000"
9597
EXACT_REVIEW_PUBLICATION_BATCH_DISPATCH_RESERVATION_MS = "600000"
9698
REVIEW_OBSERVABILITY_REQUIRED = "0"
9799
REVIEW_RECOVERY_ENABLED = "0"

‎scripts/exact-review-dead-letter-operator.mjs‎

Lines changed: 58 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,19 @@ const MAX_RECONCILE_RECOVERIES = 10;
1212
const MAX_RESOLUTION_IDS = 20;
1313
const MAX_INVENTORY_ROWS = 10_000;
1414
const MAX_RECONCILE_INVENTORY_PAGES = 250;
15+
const MAX_RECONCILE_INVENTORY_REFRESHES = 2;
1516
const GRAPHQL_IDENTITY_BATCH_SIZE = 40;
1617
const ACTIVE_RECOVERY_REASONS = new Set(["fresh_review_already_active", "publication_item_active"]);
1718
const IDEMPOTENCY_KEY = /^[A-Za-z0-9:._-]{1,200}$/;
1819

20+
class DeadLetterInventoryChangedError extends Error {
21+
constructor(summary) {
22+
super("dead-letter cleanup changed during reconciliation; refusing stale recovery");
23+
this.name = "DeadLetterInventoryChangedError";
24+
this.summary = summary;
25+
}
26+
}
27+
1928
const HELP = `Usage:
2029
node scripts/exact-review-dead-letter-operator.mjs --action <inventory|recover-fresh|resolve|reconcile> [options]
2130
@@ -46,7 +55,7 @@ async function main(argv) {
4655
throw new Error("EXACT_REVIEW_QUEUE_URL and CLAWSWEEPER_WEBHOOK_SECRET are required");
4756
}
4857

49-
const inventory = await loadInventory({
58+
let inventory = await loadInventory({
5059
queueUrl,
5160
secret,
5261
...(args.action === "reconcile" ? { maxPages: MAX_RECONCILE_INVENTORY_PAGES } : {}),
@@ -60,7 +69,40 @@ async function main(argv) {
6069
}
6170

6271
if (args.action === "reconcile") {
63-
await reconcileDeadLetters({ inventory, queueUrl, secret, args });
72+
const progress = { summary: null };
73+
for (let refreshes = 0; refreshes <= MAX_RECONCILE_INVENTORY_REFRESHES; refreshes += 1) {
74+
try {
75+
await reconcileDeadLetters({ inventory, queueUrl, secret, args, progress });
76+
return;
77+
} catch (error) {
78+
if (!(error instanceof DeadLetterInventoryChangedError)) throw error;
79+
// Guarded resolution is one Worker transaction: an inventory race skips
80+
// every requested row. Refuse recovery if that safety contract changes.
81+
if (error.summary.resolved !== 0 || error.summary.unparked !== 0) {
82+
throw new Error("guarded dead-letter cleanup was not atomic; refusing stale recovery");
83+
}
84+
if (
85+
refreshes === MAX_RECONCILE_INVENTORY_REFRESHES ||
86+
progress.summary.inspected_targets >= args.maxTargets
87+
) {
88+
// Never recover against stale aliases if producers keep changing the
89+
// inventory faster than this bounded operator can inspect it. Keep
90+
// the original target cap and accumulated counters across refreshes.
91+
printResult({
92+
...progress.summary,
93+
inventory_changed: true,
94+
skipped_rows: error.summary.skipped,
95+
});
96+
return;
97+
}
98+
inventory = await loadInventory({
99+
queueUrl,
100+
secret,
101+
maxPages: MAX_RECONCILE_INVENTORY_PAGES,
102+
});
103+
await writeFile(args.output, `${JSON.stringify(inventory, null, 2)}\n`, "utf8");
104+
}
105+
}
64106
return;
65107
}
66108

@@ -192,10 +234,10 @@ function boundedInteger(value, flag, minimum, maximum) {
192234
return parsed;
193235
}
194236

195-
async function reconcileDeadLetters({ inventory, queueUrl, secret, args }) {
237+
async function reconcileDeadLetters({ inventory, queueUrl, secret, args, progress }) {
196238
const initialPressure = await readQueuePressure(queueUrl);
197239
const openIds = new Set(inventory.dead_letters.map((row) => row.dead_letter_id));
198-
const summary = {
240+
const summary = (progress.summary ??= {
199241
action: "reconcile",
200242
dry_run: !args.execute,
201243
inventory_complete: inventory.complete,
@@ -208,7 +250,9 @@ async function reconcileDeadLetters({ inventory, queueUrl, secret, args }) {
208250
duplicate_rows: 0,
209251
active_review_rows: 0,
210252
skipped_targets: 0,
211-
};
253+
});
254+
summary.inventory_complete = inventory.complete;
255+
summary.queue_pressure = initialPressure.status;
212256
const groups = new Map();
213257
const invalidRows = [];
214258
for (const row of inventory.dead_letters) {
@@ -236,10 +280,10 @@ async function reconcileDeadLetters({ inventory, queueUrl, secret, args }) {
236280
execute: args.execute,
237281
openIds,
238282
});
239-
summary.resolved_rows = resolution.resolved;
240-
summary.invalid_rows = resolution.resolved;
283+
summary.resolved_rows += resolution.resolved;
284+
summary.invalid_rows += resolution.resolved;
241285
}
242-
summary.skipped_targets = groups.size;
286+
summary.skipped_targets += groups.size;
243287
printResult(summary);
244288
return;
245289
}
@@ -257,18 +301,18 @@ async function reconcileDeadLetters({ inventory, queueUrl, secret, args }) {
257301
execute: args.execute,
258302
openIds,
259303
});
260-
summary.resolved_rows = resolution.resolved;
261-
summary.invalid_rows = resolution.resolved;
304+
summary.resolved_rows += resolution.resolved;
305+
summary.invalid_rows += resolution.resolved;
262306
}
263-
summary.skipped_targets = groups.size;
307+
summary.skipped_targets += groups.size;
264308
printResult(summary);
265309
return;
266310
}
267311
const canonicalGroups = new Map();
268312
for (const group of groups.values()) {
269313
const live = identities.get(normalizeRecoveryTargetKey(group.target));
270314
if (!live || !["open", "closed"].includes(live.state)) {
271-
summary.skipped_targets = groups.size;
315+
summary.skipped_targets += groups.size;
272316
printResult(summary);
273317
return;
274318
}
@@ -346,7 +390,7 @@ async function reconcileDeadLetters({ inventory, queueUrl, secret, args }) {
346390
(!row.fresh_recovery.source_head_sha ||
347391
row.fresh_recovery.source_head_sha === live.head_sha),
348392
);
349-
if (!primary || recoveries.length >= args.maxRecoveries) {
393+
if (!primary || summary.recovered_targets + recoveries.length >= args.maxRecoveries) {
350394
summary.skipped_targets += 1;
351395
continue;
352396
}
@@ -557,7 +601,7 @@ async function reconcileResolve({
557601
});
558602
const summary = mutationSummary("resolve", result);
559603
if (summary.resolved !== rows.length || summary.skipped !== 0) {
560-
throw new Error("dead-letter cleanup changed during reconciliation; refusing stale recovery");
604+
throw new DeadLetterInventoryChangedError(summary);
561605
}
562606
for (const row of rows) openIds?.delete(row.dead_letter_id);
563607
return summary;

‎src/clawsweeper-action-commands.ts‎

Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
import { readFileSync, statSync } from "node:fs";
2+
import { join, relative, resolve } from "node:path";
3+
import { isActionEventPublishPath } from "./action-ledger-paths.js";
4+
import {
5+
ACTION_EVENT_SHARD_IMPORT_MAX_PUBLISH_PATHS,
6+
importActionEventShards,
7+
interruptOpenWorkflowActionEvents,
8+
workflowActionProducer,
9+
} from "./action-ledger-runtime.js";
10+
import { ACTION_EVENT_REASON_CODES } from "./action-ledger.js";
11+
import { boolArg, optionalNumberArg, stringArg, type Args } from "./clawsweeper-args.js";
12+
import { UserFacingCommandError } from "./command.js";
13+
import { type RepositoryProfile } from "./repository-profiles.js";
14+
import { publishStateBlob } from "./state-blob-client.js";
15+
16+
interface CreateActionCommandsDependencies {
17+
defaultClosedDir: (profile?: RepositoryProfile) => string;
18+
defaultItemsDir: (profile?: RepositoryProfile) => string;
19+
repoFromArgs: (args: Args) => RepositoryProfile;
20+
ROOT: string;
21+
updateDashboard: (itemsDir?: string, closedDir?: string) => void;
22+
}
23+
24+
export function createActionCommands(dependencies: CreateActionCommandsDependencies) {
25+
const { defaultClosedDir, defaultItemsDir, repoFromArgs, ROOT, updateDashboard } = dependencies;
26+
27+
function publishActionEventsCommand(args: Args): void {
28+
const sourceRoot = resolve(
29+
stringArg(args.source_root, join(ROOT, ".clawsweeper-repair", "action-ledger-download")),
30+
);
31+
const stateRoot = resolve(stringArg(args.state_root, ROOT));
32+
const expectedProducerJob = stringArg(args.expected_producer_job, "");
33+
if (!expectedProducerJob) {
34+
throw new UserFacingCommandError("--expected-producer-job is required");
35+
}
36+
const expectedProducerRunAttempt = optionalNumberArg(args.expected_producer_run_attempt);
37+
if (
38+
expectedProducerRunAttempt !== undefined &&
39+
(!Number.isInteger(expectedProducerRunAttempt) || expectedProducerRunAttempt < 1)
40+
) {
41+
throw new UserFacingCommandError(
42+
"--expected-producer-run-attempt must be a positive integer",
43+
);
44+
}
45+
const expectedProducerRunId = stringArg(args.expected_producer_run_id, "");
46+
if (expectedProducerRunId && !/^\d{1,30}$/.test(expectedProducerRunId)) {
47+
throw new UserFacingCommandError(
48+
"--expected-producer-run-id must be a numeric workflow run ID",
49+
);
50+
}
51+
const expectedProducerSha = stringArg(args.expected_producer_sha, "");
52+
if (expectedProducerSha && !/^[0-9a-f]{40}$/.test(expectedProducerSha)) {
53+
throw new UserFacingCommandError("--expected-producer-sha must be a lowercase commit SHA");
54+
}
55+
const currentProducer = workflowActionProducer("action_event_publisher");
56+
const result = importActionEventShards(sourceRoot, stateRoot, {
57+
expectedProducer: {
58+
repository: currentProducer.repository,
59+
sha: expectedProducerSha || currentProducer.sha,
60+
workflow: currentProducer.workflow,
61+
job: expectedProducerJob,
62+
runId: expectedProducerRunId || currentProducer.runId,
63+
runAttempt: expectedProducerRunAttempt ?? currentProducer.runAttempt,
64+
},
65+
});
66+
console.log(JSON.stringify(result, null, 2));
67+
}
68+
69+
const ACTION_EVENT_PUBLISH_PATH_FILE_MAX_BYTES =
70+
ACTION_EVENT_SHARD_IMPORT_MAX_PUBLISH_PATHS * 512;
71+
72+
function actionEventPublishPathsForTest(content: string): string[] {
73+
if (Buffer.byteLength(content, "utf8") > ACTION_EVENT_PUBLISH_PATH_FILE_MAX_BYTES) {
74+
throw new Error(
75+
`action event publish path manifest exceeds ${ACTION_EVENT_PUBLISH_PATH_FILE_MAX_BYTES} bytes`,
76+
);
77+
}
78+
const paths = content.split("\n").filter(Boolean);
79+
if (paths.length === 0) throw new Error("action event publish path manifest is empty");
80+
if (paths.length > ACTION_EVENT_SHARD_IMPORT_MAX_PUBLISH_PATHS) {
81+
throw new Error(
82+
`action event publish path manifest exceeds ${ACTION_EVENT_SHARD_IMPORT_MAX_PUBLISH_PATHS} paths`,
83+
);
84+
}
85+
let previous = "";
86+
for (const path of paths) {
87+
if (!isActionEventPublishPath(path)) {
88+
throw new Error(`invalid action event publish path: ${path}`);
89+
}
90+
if (previous && path <= previous) {
91+
throw new Error("action event publish paths must be sorted and unique");
92+
}
93+
previous = path;
94+
}
95+
return paths;
96+
}
97+
98+
async function publishActionEventPathsCommand(args: Args): Promise<void> {
99+
const pathsFile = resolve(stringArg(args.paths_file, ""));
100+
if (!pathsFile || pathsFile === ROOT) {
101+
throw new UserFacingCommandError("--paths-file is required");
102+
}
103+
const stat = statSync(pathsFile);
104+
if (!stat.isFile())
105+
throw new Error(`action event publish path manifest is not a file: ${pathsFile}`);
106+
if (stat.size > ACTION_EVENT_PUBLISH_PATH_FILE_MAX_BYTES) {
107+
throw new Error(
108+
`action event publish path manifest exceeds ${ACTION_EVENT_PUBLISH_PATH_FILE_MAX_BYTES} bytes`,
109+
);
110+
}
111+
const paths = actionEventPublishPathsForTest(readFileSync(pathsFile, "utf8"));
112+
for (const path of paths) {
113+
const source = resolve(ROOT, path);
114+
const rootRelativeSource = relative(ROOT, source);
115+
if (
116+
rootRelativeSource.startsWith("..") ||
117+
resolve(ROOT, rootRelativeSource) !== source ||
118+
!statSync(source).isFile()
119+
) {
120+
throw new Error(`action event publish path is not a regular file: ${path}`);
121+
}
122+
}
123+
const baseUrl = process.env.QUEUE_URL ?? process.env.CLAWSWEEPER_RECORDS_URL ?? "";
124+
const webhookSecret = process.env.CLAWSWEEPER_WEBHOOK_SECRET ?? "";
125+
let uploaded = 0;
126+
let unchanged = 0;
127+
for (const path of paths) {
128+
const result = await publishStateBlob({
129+
baseUrl,
130+
webhookSecret,
131+
path,
132+
content: readFileSync(resolve(ROOT, path)),
133+
});
134+
if (result.unchanged) unchanged += 1;
135+
else uploaded += 1;
136+
}
137+
console.log(
138+
JSON.stringify({ result: "published", path_count: paths.length, uploaded, unchanged }),
139+
);
140+
}
141+
142+
function isExplicitActionLedgerCommand(command: string): boolean {
143+
return (
144+
command === "finalize-action-events" ||
145+
command === "publish-action-events" ||
146+
command === "publish-action-event-paths"
147+
);
148+
}
149+
150+
function dashboardCommand(args: Args): void {
151+
repoFromArgs(args);
152+
updateDashboard(
153+
resolve(stringArg(args.items_dir, defaultItemsDir())),
154+
resolve(stringArg(args.closed_dir, defaultClosedDir())),
155+
);
156+
}
157+
158+
function finalizeActionEventsCommand(args: Args): void {
159+
if (!boolArg(args.interrupt_open_attempts)) return;
160+
const reason = stringArg(args.reason, ACTION_EVENT_REASON_CODES.timeout);
161+
if (
162+
reason !== ACTION_EVENT_REASON_CODES.timeout &&
163+
reason !== ACTION_EVENT_REASON_CODES.cancelled &&
164+
reason !== ACTION_EVENT_REASON_CODES.workflowFailed
165+
) {
166+
throw new UserFacingCommandError(
167+
`Unsupported --reason for interrupted action events: ${reason}`,
168+
);
169+
}
170+
const interrupted = interruptOpenWorkflowActionEvents(ROOT, { reasonCode: reason });
171+
if (interrupted > 0) {
172+
console.error(
173+
`[action-ledger] recorded ${interrupted} ${reason} terminal event${
174+
interrupted === 1 ? "" : "s"
175+
}`,
176+
);
177+
}
178+
}
179+
180+
return {
181+
actionEventPublishPathsForTest,
182+
dashboardCommand,
183+
finalizeActionEventsCommand,
184+
isExplicitActionLedgerCommand,
185+
publishActionEventPathsCommand,
186+
publishActionEventsCommand,
187+
};
188+
}

0 commit comments

Comments
 (0)