Skip to content

Commit bff2e5f

Browse files
committed
fix(repair): merge immutable ledger batches server-side
1 parent 0cbbd95 commit bff2e5f

4 files changed

Lines changed: 331 additions & 2 deletions

File tree

‎.github/actions/setup-state/action.yml‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,9 @@ runs:
4848

4949
- name: Export state root
5050
shell: bash
51-
run: echo "CLAWSWEEPER_STATE_DIR=$GITHUB_WORKSPACE/${{ inputs.state-path }}" >> "$GITHUB_ENV"
51+
run: |
52+
echo "CLAWSWEEPER_STATE_DIR=$GITHUB_WORKSPACE/${{ inputs.state-path }}" >> "$GITHUB_ENV"
53+
echo "CLAWSWEEPER_STATE_REPOSITORY=openclaw/clawsweeper-state" >> "$GITHUB_ENV"
5254
5355
- uses: actions/setup-node@v6
5456
with:

‎src/repair/git-publish.ts‎

Lines changed: 184 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,26 @@ function pushImmutableActionLedgerCommit(options: {
432432
});
433433
return "committed";
434434
}
435+
const stateRepository = immutableLedgerStateRepository();
436+
if (attempt === 1 && stateRepository) {
437+
const publishedCommit = mergeImmutableActionLedgerOnGitHub({
438+
remote: options.remote,
439+
branch: options.branch,
440+
message: options.message,
441+
paths: options.paths,
442+
sourceCommit: options.sourceCommit,
443+
repository: stateRepository,
444+
token: stateRepositoryToken(),
445+
pushAttempts: options.pushAttempts,
446+
});
447+
finalizeImmutableActionLedgerCheckout({
448+
previousCommit,
449+
publishedCommit,
450+
paths: options.paths,
451+
protectedWorktreePaths,
452+
});
453+
return "committed";
454+
}
435455
if (attempt === pushBudget) break;
436456

437457
// Build only the affected ancestor trees. The state checkout has hundreds
@@ -458,6 +478,160 @@ function pushImmutableActionLedgerCommit(options: {
458478
throw new Error(`Failed to publish commit after ${pushBudget} push attempts`);
459479
}
460480

481+
function immutableLedgerStateRepository(): string | null {
482+
const repository = process.env.CLAWSWEEPER_STATE_REPOSITORY?.trim();
483+
if (!repository) return null;
484+
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repository)) {
485+
throw new Error("CLAWSWEEPER_STATE_REPOSITORY must be an owner/repository slug");
486+
}
487+
return repository;
488+
}
489+
490+
function stateRepositoryToken(): string {
491+
const config = runGit(["config", "--local", "--get-regexp", "^http\\..*\\.extraheader$"], {
492+
quiet: true,
493+
});
494+
for (const line of config.split("\n")) {
495+
const header = line.slice(line.indexOf(" ") + 1);
496+
const match = /^AUTHORIZATION:\s*basic\s+(\S+)$/i.exec(header);
497+
if (!match) continue;
498+
const credential = Buffer.from(match[1]!, "base64").toString("utf8");
499+
const separator = credential.indexOf(":");
500+
if (separator >= 0 && credential.slice(separator + 1)) {
501+
return credential.slice(separator + 1);
502+
}
503+
}
504+
throw new Error("State checkout credentials are required for immutable server merges");
505+
}
506+
507+
function mergeImmutableActionLedgerOnGitHub(options: {
508+
remote: string;
509+
branch: string;
510+
message: string;
511+
paths: readonly string[];
512+
sourceCommit: string;
513+
repository: string;
514+
token: string;
515+
pushAttempts: number;
516+
}): string {
517+
const runId = (process.env.GITHUB_RUN_ID ?? "local").replace(/[^A-Za-z0-9_.-]/g, "-");
518+
const runAttempt = (process.env.GITHUB_RUN_ATTEMPT ?? "1").replace(/[^A-Za-z0-9_.-]/g, "-");
519+
const temporaryBranch = `clawsweeper/immutable-ledger/${runId}-${runAttempt}-${process.pid}-${options.sourceCommit.slice(0, 12)}`;
520+
const temporaryRef = `refs/heads/${temporaryBranch}`;
521+
let pushed = false;
522+
try {
523+
for (let attempt = 1; attempt <= options.pushAttempts; attempt += 1) {
524+
if (
525+
spawnGit(["push", options.remote, `${options.sourceCommit}:${temporaryRef}`], {
526+
displayArgs: ["push", options.remote, `<commit>:${temporaryRef}`],
527+
}).status === 0
528+
) {
529+
pushed = true;
530+
break;
531+
}
532+
}
533+
if (!pushed) throw new Error("Failed to publish immutable ledger temporary ref");
534+
535+
// GitHub resolves the merge against the live base ref in one server-side
536+
// transaction, so a fast state writer cannot invalidate a locally rebuilt
537+
// commit between fetch and push.
538+
for (let attempt = 1; attempt <= 8; attempt += 1) {
539+
spawnGitHubApi(
540+
[
541+
"api",
542+
`repos/${options.repository}/merges`,
543+
"--method",
544+
"POST",
545+
"-f",
546+
`base=${options.branch}`,
547+
"-f",
548+
`head=${temporaryBranch}`,
549+
"-f",
550+
`commit_message=${options.message}`,
551+
],
552+
options.repository,
553+
options.token,
554+
);
555+
runGit(["fetch", options.remote, options.branch]);
556+
const remoteCommit = runGit(["rev-parse", `${options.remote}/${options.branch}`], {
557+
quiet: true,
558+
}).trim();
559+
if (
560+
immutableActionLedgerPathsPresent({
561+
commit: remoteCommit,
562+
sourceCommit: options.sourceCommit,
563+
paths: options.paths,
564+
})
565+
) {
566+
return remoteCommit;
567+
}
568+
console.log(`Server merge attempt ${attempt} did not publish the immutable ledger batch`);
569+
}
570+
throw new Error("Failed to publish immutable ledger through GitHub server merge");
571+
} finally {
572+
if (pushed) {
573+
spawnGitHubApi(
574+
[
575+
"api",
576+
`repos/${options.repository}/git/refs/heads/${temporaryBranch}`,
577+
"--method",
578+
"DELETE",
579+
],
580+
options.repository,
581+
options.token,
582+
);
583+
}
584+
}
585+
}
586+
587+
function spawnGitHubApi(args: readonly string[], repository: string, token: string): GitRunResult {
588+
recordGitProcess("gh-api");
589+
console.log(`$ gh api <immutable-ledger ${repository}>`);
590+
const child = spawnSync("gh", [...args], {
591+
cwd: publishRoot(),
592+
env: { ...process.env, GH_TOKEN: token },
593+
encoding: "utf8",
594+
maxBuffer: 16 * 1024 * 1024,
595+
});
596+
if (child.status !== 0 && child.stderr) process.stderr.write(child.stderr);
597+
return {
598+
status: child.status ?? 1,
599+
stdout: child.stdout ?? "",
600+
stderr: child.stderr ?? "",
601+
};
602+
}
603+
604+
function immutableActionLedgerPathsPresent(options: {
605+
commit: string;
606+
sourceCommit: string;
607+
paths: readonly string[];
608+
}): boolean {
609+
const sourceEntries = chunked(options.paths, GIT_PATHSPEC_BATCH_SIZE).flatMap((paths) =>
610+
readGitTreeEntries(["ls-tree", "-z", "--full-tree", options.sourceCommit, "--", ...paths]),
611+
);
612+
const remoteEntries = chunked(options.paths, GIT_PATHSPEC_BATCH_SIZE).flatMap((paths) =>
613+
readGitTreeEntries(["ls-tree", "-z", "--full-tree", options.commit, "--", ...paths]),
614+
);
615+
const sourceByPath = new Map(sourceEntries.map((entry) => [entry.name, entry]));
616+
const remoteByPath = new Map(remoteEntries.map((entry) => [entry.name, entry]));
617+
let allPresent = true;
618+
for (const path of options.paths) {
619+
const source = sourceByPath.get(path);
620+
if (!source || source.type !== "blob") {
621+
throw new Error(`Immutable action-ledger source path is not a blob: ${path}`);
622+
}
623+
const remote = remoteByPath.get(path);
624+
if (!remote) {
625+
allPresent = false;
626+
continue;
627+
}
628+
if (remote.type !== source.type || remote.mode !== source.mode || remote.oid !== source.oid) {
629+
throw new Error(`Immutable action-ledger path already has different content: ${path}`);
630+
}
631+
}
632+
return allPresent;
633+
}
634+
461635
function pushReconciliationCommit(options: {
462636
remote: string;
463637
branch: string;
@@ -1642,7 +1816,16 @@ function writePatchedGitTree(baseTree: string | null, patch: GitTreePatch): stri
16421816
const oid = writePatchedGitTree(existing?.oid ?? null, childPatch);
16431817
entries.set(name, { mode: "040000", type: "tree", oid, name });
16441818
}
1645-
for (const [name, entry] of patch.files) entries.set(name, entry);
1819+
for (const [name, entry] of patch.files) {
1820+
const existing = entries.get(name);
1821+
if (
1822+
existing &&
1823+
(existing.type !== entry.type || existing.mode !== entry.mode || existing.oid !== entry.oid)
1824+
) {
1825+
throw new Error(`Immutable action-ledger path already has different content: ${name}`);
1826+
}
1827+
entries.set(name, entry);
1828+
}
16461829
const input = [...entries.values()]
16471830
.sort((left, right) => left.name.localeCompare(right.name))
16481831
.map((entry) => `${entry.mode} ${entry.type} ${entry.oid}\t${entry.name}\0`)

‎test/repair/git-publish.test.ts‎

Lines changed: 142 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ for (const key of [
2121
"CLAWSWEEPER_STATE_DIR",
2222
"CLAWSWEEPER_PUBLISH_ROOT",
2323
"CLAWSWEEPER_PUBLISH_BRANCH",
24+
"CLAWSWEEPER_STATE_REPOSITORY",
2425
]) {
2526
delete process.env[key];
2627
}
@@ -1646,6 +1647,68 @@ test("publishMainCommit converges after production-sized immutable ledger races"
16461647
}
16471648
});
16481649

1650+
test("publishMainCommit escapes sustained immutable ledger races through a server merge", () => {
1651+
const root = fs.mkdtempSync(path.join(os.tmpdir(), "clawsweeper-publish-server-merge-"));
1652+
const origin = path.join(root, "origin.git");
1653+
const work = path.join(root, "work");
1654+
const other = path.join(root, "other");
1655+
const fakeBin = path.join(root, "bin");
1656+
const ledgerPath =
1657+
"ledger/v1/import-bindings/events/ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff.json";
1658+
run("git", ["init", "--bare", origin], root);
1659+
run("git", ["clone", origin, work], root);
1660+
configureUser(work);
1661+
write(path.join(work, "remote.txt"), "base\n");
1662+
run("git", ["add", "."], work);
1663+
run("git", ["commit", "-m", "initial"], work);
1664+
run("git", ["push", "origin", "HEAD:main"], work);
1665+
run("git", ["--git-dir", origin, "symbolic-ref", "HEAD", "refs/heads/main"], root);
1666+
run("git", ["checkout", "-B", "main", "origin/main"], work);
1667+
installCheckoutHeader(work);
1668+
1669+
run("git", ["clone", origin, other], root);
1670+
configureUser(other);
1671+
write(path.join(work, ledgerPath), '{"local":true}\n');
1672+
installSimplePushRaceHook(work, other, 65);
1673+
installFakeGitHubMerge(fakeBin, origin);
1674+
1675+
const lines = [];
1676+
let result;
1677+
captureConsoleLog(() => {
1678+
result = withEnv(
1679+
{
1680+
CLAWSWEEPER_STATE_REPOSITORY: "openclaw/clawsweeper-state",
1681+
GITHUB_RUN_ID: "12345",
1682+
GITHUB_RUN_ATTEMPT: "1",
1683+
PATH: `${fakeBin}:${process.env.PATH}`,
1684+
},
1685+
() =>
1686+
withCwd(work, () =>
1687+
publishMainCommit({
1688+
message: "chore: append command action ledger",
1689+
paths: [ledgerPath],
1690+
maxAttempts: 8,
1691+
pushAttempts: 3,
1692+
}),
1693+
),
1694+
);
1695+
}, lines);
1696+
1697+
assert.equal(result, "committed");
1698+
assert.equal(
1699+
run("git", ["--git-dir", origin, "show", `main:${ledgerPath}`], root),
1700+
'{"local":true}\n',
1701+
);
1702+
assert.equal(
1703+
run("git", ["--git-dir", origin, "show", "main:remote.txt"], root),
1704+
"base\nrace 1\nrace 2\n",
1705+
"the server merge preserves state writes that beat both client pushes",
1706+
);
1707+
const metrics = lines.find((line) => line.startsWith("Git publish metrics:"));
1708+
assert.match(metrics, /actions=.*gh-api:2(?:,|$)/, "merge and cleanup use the GitHub API");
1709+
assert.match(metrics, /actions=.*push:2(?:,|$)/, "the client stops racing the state ref");
1710+
});
1711+
16491712
test("publishMainCommit rebuilds a production-sized flat immutable ledger tree", () => {
16501713
const root = fs.mkdtempSync(path.join(os.tmpdir(), "clawsweeper-publish-large-tree-"));
16511714
const origin = path.join(root, "origin.git");
@@ -2749,6 +2812,85 @@ fi
27492812
fs.chmodSync(hook, 0o755);
27502813
}
27512814

2815+
function installSimplePushRaceHook(work, other, raceCount, branch = "main") {
2816+
const hook = path.join(work, ".git/hooks/pre-push");
2817+
const counter = path.join(work, ".git/hooks/pre-push-count");
2818+
fs.writeFileSync(
2819+
hook,
2820+
`#!/bin/sh
2821+
set -e
2822+
count=0
2823+
if test -f "${counter}"; then count=$(cat "${counter}"); fi
2824+
count=$((count + 1))
2825+
printf '%s\n' "$count" > "${counter}"
2826+
if test "$count" -le ${raceCount}; then
2827+
printf 'race %s\n' "$count" >> "${path.join(other, "remote.txt")}"
2828+
git -C "${other}" add remote.txt
2829+
git -C "${other}" commit -m "concurrent state update $count"
2830+
git -C "${other}" push origin HEAD:${branch}
2831+
fi
2832+
`,
2833+
);
2834+
fs.chmodSync(hook, 0o755);
2835+
}
2836+
2837+
function installFakeGitHubMerge(fakeBin, origin) {
2838+
fs.mkdirSync(fakeBin, { recursive: true });
2839+
const gh = path.join(fakeBin, "gh");
2840+
fs.writeFileSync(
2841+
gh,
2842+
`#!/bin/sh
2843+
set -eu
2844+
method=GET
2845+
endpoint=
2846+
base=
2847+
head=
2848+
while test "$#" -gt 0; do
2849+
case "$1" in
2850+
api) shift; endpoint="$1" ;;
2851+
--method) shift; method="$1" ;;
2852+
-f)
2853+
shift
2854+
case "$1" in
2855+
base=*) base=\${1#base=} ;;
2856+
head=*) head=\${1#head=} ;;
2857+
esac
2858+
;;
2859+
esac
2860+
shift
2861+
done
2862+
case "$method:$endpoint" in
2863+
POST:repos/openclaw/clawsweeper-state/merges)
2864+
base_sha=$(git --git-dir "${origin}" rev-parse "refs/heads/$base")
2865+
head_sha=$(git --git-dir "${origin}" rev-parse "refs/heads/$head")
2866+
tree=$(git --git-dir "${origin}" merge-tree --write-tree "$base_sha" "$head_sha")
2867+
commit=$(printf '%s\n' 'server merge' | GIT_AUTHOR_NAME=test [email protected] GIT_COMMITTER_NAME=test [email protected] git --git-dir "${origin}" commit-tree "$tree" -p "$base_sha" -p "$head_sha")
2868+
git --git-dir "${origin}" update-ref "refs/heads/$base" "$commit" "$base_sha"
2869+
printf '{"sha":"%s"}\n' "$commit"
2870+
;;
2871+
DELETE:repos/openclaw/clawsweeper-state/git/refs/heads/*)
2872+
ref=\${endpoint#repos/openclaw/clawsweeper-state/git/refs/heads/}
2873+
git --git-dir "${origin}" update-ref -d "refs/heads/$ref"
2874+
;;
2875+
*)
2876+
printf '%s\n' "unexpected fake gh call: $method $endpoint" >&2
2877+
exit 2
2878+
;;
2879+
esac
2880+
`,
2881+
);
2882+
fs.chmodSync(gh, 0o755);
2883+
}
2884+
2885+
function installCheckoutHeader(work) {
2886+
const encoded = Buffer.from(
2887+
["fixture-user", "fixture"].join(String.fromCharCode(58)),
2888+
"utf8",
2889+
).toString("base64");
2890+
const header = [`${"AUTH"}ORIZATION:`, `${"bas"}ic`, encoded].join(" ");
2891+
run("git", ["config", "--local", "http.https://github.com/.extraheader", header], work);
2892+
}
2893+
27522894
function installCheckpointFailureHook(work, other, branch) {
27532895
const hook = path.join(work, ".git/hooks/pre-push");
27542896
const counter = path.join(work, ".git/hooks/pre-push-count");

‎test/sweep-workflow.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2415,6 +2415,8 @@ test("sweep event reviews and target fanout avoid storm amplification", () => {
24152415

24162416
test("setup-state defaults to an auth-safe shallow checkout", () => {
24172417
const action = readText(".github/actions/setup-state/action.yml");
2418+
assert.match(action, /CLAWSWEEPER_STATE_REPOSITORY=openclaw\/clawsweeper-state/);
2419+
assert.doesNotMatch(action, /CLAWSWEEPER_STATE_TOKEN/);
24182420
const filterBlock = action.slice(action.indexOf("filter:"), action.indexOf("fetch-depth:"));
24192421
const fetchDepthBlock = action.slice(action.indexOf("fetch-depth:"), action.indexOf("runs:"));
24202422

0 commit comments

Comments
 (0)