Skip to content

fix(infra): decide the history-blobs lock with a kernel lock, not mkdir - #199982

Open
Szqub wants to merge 2 commits into
openclaw:mainfrom
Szqub:fix/kernel-history-blobs-lock
Open

Szqub wants to merge 2 commits into
openclaw:mainfrom
Szqub:fix/kernel-history-blobs-lock

Conversation

@Szqub

@Szqub Szqub commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Related: #198531

What Problem This Solves

Concurrent git log -S and git blame history reads can start overlapping blob fetches into one shared object store when an older shim's openclaw-history-blobs.lock marker is present, and a leftover marker whose pid was reused by an unrelated live process makes every content search wait on it forever.

User Impact

Agents in linked worktrees share one history-prefetch lock: one fetch runs at a time, and a stale legacy marker costs at most 30 s per invocation instead of blocking every later search. The bounded wait now runs before the kernel lock, so N parallel callers wait 30 s together rather than k x 30 s in lock order. When the wait expires, that invocation skips the prefetch: non-show content searches run offline and exit 2 with the budget guidance, while show keeps its speculative native fallback. The marker is never removed, so the 30 s cost repeats while the pid lives. There is no user-visible UI change.

Why This Change Was Made

prepare_blobs serialised prefetches with a mkdir directory lock plus an owner pid file. That protocol removes and recreates the lock pathname: a waiter that decides the owner is dead deletes the record and the directory, so it can delete the lock a successor has just created and two callers can then fetch into the same object store at once. A leftover pid value that now belongs to a live process also resets the attempt counter forever. In the base, a live old owner reset that counter and the wait had no bound.

The lock is now a kernel lock on a file the shim never unlinks. The open and the lock run in a nested subshell so a failed exec cannot end the caller and the fallback stays reachable:

if ! (
  { exec 9>>"$common/openclaw-history-blobs.lock.kernel"; } 2>/dev/null || exit 1
  case $(uname -s) in
    Linux) flock -x 9 2>/dev/null || exit 1 ;;
    *)     lockf -s 9 2>/dev/null || exit 1 ;;
  esac
  ...
); then
  # mkdir fallback, no reclaim
fi

The kernel lock file stays in .git as an empty file; it is never removed. With no unlink there is no reclaim step and no interval in which two callers both believe they own the lock. The descriptor is opened inside the prepare_blobs subshell, so the kernel releases the lock when the subshell exits and no cleanup trap is needed.

An old shim cannot see the kernel lock: an old process that starts while a new prefetch is running can still create its directory marker and fetch beside it. The upgrade window is one-sided. The new side reads the old marker before taking the kernel lock and serves a live owner first; that orders the common case without changing processes that are already running. A live old owner with a large batch used to wait without bound; the new side ends the wait after 30 s, skips its own prefetch, and leaves the old owner to finish.

Because kill -0 only shows that a pid exists, the legacy wait keeps the 300-iteration sleep 0.1 bound the directory lock had. It runs before the kernel lock, so parallel callers time out together instead of queueing for another 30 s each. A timed-out caller skips the prefetch; prepared_blobs is already set for non-show content searches, so they take the failed-preparation path (offline, exit 2, budget error) rather than starting a lazy fetch beside the old owner. show keeps the speculative native fallback that #198531 gives it.

If flock or lockf -s is missing, or the platform rejects the descriptor form, the shim falls back to an mkdir mutex without the old reclaim step. Cleanup removes the record only while the process still owns the pid file, so it cannot delete a successor's lock. If the fallback owner is killed before cleanup, the directory stays permanently; every later prefetch on that path waits 30 s and skips until it is removed. The directory lives in the git-common-dir, not in a linked worktree's .git file. Stop every process that may use it, then remove it with rm -r "$(git rev-parse --git-common-dir)/openclaw-history-blobs.lock.fallback". This keeps a clean system working instead of turning every content search into exit 2. The lockf -s fd form exists in FreeBSD since December 2023; the minimum macOS version is UNKNOWN, and older userlands take the fallback.

The kernel lock and the fallback mkdir mutex are different paths. Two environments that share a .git but resolve different binaries, for example a container with a bind mount and its host, do not exclude each other; the old directory marker is the only cross-environment signal.

Scope: two files, +450/-23. The shim replaces the twenty-line reclaim protocol with the kernel lock, the portable fallback, and the bounded legacy read; the history test adds the stale-marker race, the fallback cases, the release-before-limit path, and the updated legacy timeout. The reproduction script stays out of the diff and is in the collapsed block below.

Evidence

Environment: ephemeral Ubuntu 26.04.1 sandbox (kernel 6.12.114, node v24.22.3, git 2.53.0). Base 22614d5b0e81fc68cbbbf6bdcdd34301a3e02658; patch applied on a clean tree; git write-tree = 12ab4e144960048691edd2a96aaaab64ab492b51.

Focused tests:

command exit result
node scripts/run-vitest.mjs run src/infra/agent-git-shim.history.test.ts --maxWorkers=1 0 14 passed (100 s)
node scripts/run-vitest.mjs run src/infra/agent-git-shim.test.ts --maxWorkers=1 0 2 passed (37 s)
node scripts/run-tsgo.mjs -p tsconfig.core.json --incremental 0 no diagnostics (25 s)
node scripts/run-format.mts --check 0 59 137 files (20 s)
oxlint --config .oxlintrc.json on the shim and the history test 0 0 warnings, 0 errors
check-test-lines-ratchet.mts 0 +386 test lines, allowance 400
check-max-lines-ratchet.mts 0 389 grandfathered suppressions
git diff --check 0

The timeout tests use a fake sleep wrapper to assert the 299-iteration bound and the release-before-limit path without real 30 s waits; the real 30 s and 45 s measurements are in the proof script below.

Behavior, before and after. Real shim, real Git subprocesses, two linked worktrees, local file:// fixture; no network, credentials, or private paths. A path wrapper journals every fetch boundary and holds the fetch open long enough that an overlap cannot hide inside a few milliseconds. The reclaim runs use the same dead marker and the same delayed rm on both shims, so the comparison is symmetric. The journal is ordered by append order, not by wall-clock timestamps.

[base-reclaim-race]       maxFetchOverlap=2  fetch-enter,fetch-enter,fetch-leave,fetch-leave
[patched-reclaim]         maxFetchOverlap=1  fetch-enter,fetch-leave,fetch-enter,fetch-leave
[patched-legacy-timeout]  30,472 ms, exit 2, 0 new packs, budget error
[base-legacy-timeout]     killed at 45,007 ms (SIGKILL), no fetch started
  • Base shim, stale marker whose pid is dead, two waiters: the second waiter removes the first waiter's pid and directory and both fetches overlap (enter,enter,leave,leave). This is the failure the kernel lock removes.
  • Patched shim, the same marker and the same delayed rm: the dead pid is ignored, the kernel lock serialises the two readers (enter,leave,enter,leave), so the old reclaim window is gone.
  • Patched shim, live legacy marker with git log -S: after 30,472 ms the prefetch is skipped, the command exits 2, prints OpenClaw: content search could not finish within the shared partial-clone blob budget; command stopped without lazy fetching..., and creates no pack.
  • Base shim, the same live marker: the attempt counter resets while kill -0 succeeds, so the command did not return and was killed by a hard 45 s timeout.

The trace is reproducible with the script in the collapsed block below; save it outside the checkout, pass the base ref as the first argument (or set OPENCLAW_BASE), and run it from the repository root. The script prints the journal, the elapsed times, and the exit codes for all four runs.

Not run: macOS and FreeBSD lockf -s 9 (only Linux executed; the descriptor form is documented by Apple and FreeBSD, and the fallback covers older userlands); Windows is not materialised for this shim.

Reproduction script (history-lock-proof.mjs)
#!/usr/bin/env node
/**
 * Manual proof for the history-blobs lock.
 *
 * Runs four scenarios with the real shim and real Git:
 *  1. base shim, stale marker + delayed rm -> overlapping fetches;
 *  2. patched shim, the same marker -> serialised fetches;
 *  3. patched shim, live legacy owner -> 30 s bound, offline exit 2;
 *  4. base shim, the same live owner -> unbounded wait, killed by the harness.
 *
 * The fixture origin is a local file:// repository; no credentials or network.
 * The fetch journal is ordered by append order, not by wall-clock timestamps.
 * Usage: node scripts/history-lock-proof.mjs [base-ref]
 */
import { spawn, spawnSync } from "node:child_process";
import fsp from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";

const repo = process.env.OPENCLAW_REPO || process.cwd();
const baseRef = process.env.OPENCLAW_BASE || process.argv[2] || "origin/main";
const baseCommit = spawnSync("git", ["-C", repo, "rev-parse", baseRef], {
  encoding: "utf8",
}).stdout.trim();
if (!baseCommit) {
  throw new Error(`cannot resolve base ref: ${baseRef}`);
}
const root = await fsp.mkdtemp(path.join(os.tmpdir(), "openclaw-lock-proof-"));
const fixtureRoot = path.join(root, "fixture");
await fsp.mkdir(fixtureRoot);

const baseEnv = {
  ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))),
  GIT_CONFIG_NOSYSTEM: "1",
  GIT_CONFIG_GLOBAL: "/dev/null",
  GIT_ALLOW_PROTOCOL: "file",
  GIT_TERMINAL_PROMPT: "0",
  GIT_CONFIG_COUNT: "2",
  GIT_CONFIG_KEY_0: "gc.auto",
  GIT_CONFIG_VALUE_0: "0",
  GIT_CONFIG_KEY_1: "maintenance.auto",
  GIT_CONFIG_VALUE_1: "false",
};

function runGit(cwd, args, input) {
  const result = spawnSync("git", ["-C", cwd, ...args], {
    env: baseEnv,
    input,
    encoding: "utf8",
    maxBuffer: 32 * 1024 * 1024,
  });
  if (result.status !== 0) {
    throw new Error(`git ${args.join(" ")} failed: ${result.stderr || result.stdout}`);
  }
  return result.stdout;
}

function extractShim(source, label) {
  const start = source.indexOf("`");
  const end = source.lastIndexOf("`");
  if (start < 0 || end <= start) {
    throw new Error(`${label}: no template literal found`);
  }
  const body = source.slice(start + 1, end);
  // oxlint-disable-next-line no-new-func -- trusted shim template, not user input
  return new Function(`return \`${body}\`;`)();
}

const baseSource = spawnSync(
  "git",
  ["-C", repo, "show", `${baseCommit}:src/infra/agent-git-shim.ts`],
  { encoding: "utf8", maxBuffer: 32 * 1024 * 1024 },
);
if (baseSource.status !== 0) {
  throw new Error(`cannot read base shim: ${baseSource.stderr}`);
}
const patchedSource = await fsp.readFile(path.join(repo, "src/infra/agent-git-shim.ts"), "utf8");
const shims = {
  base: path.join(root, "shim-base"),
  patched: path.join(root, "shim-patched"),
};
await fsp.writeFile(shims.base, extractShim(baseSource.stdout, "base"), { mode: 0o755 });
await fsp.writeFile(shims.patched, extractShim(patchedSource, "patched"), { mode: 0o755 });

// Fixture origin: 12 commits touching two disjoint files.
const origin = path.join(fixtureRoot, "origin");
const seed = path.join(fixtureRoot, "seed");
const file = "folder/history file.txt";
const other = "other.txt";
runGit(fixtureRoot, ["init", "--initial-branch=main", origin]);
runGit(origin, ["config", "uploadpack.allowFilter", "true"]);
let importInput = "";
let content = "";
for (let index = 1; index <= 12; index++) {
  content += `history line ${index}\n`;
  const otherContent = `unrelated version ${index}\n`;
  importInput +=
    `commit refs/heads/main\n` +
    `committer Fixture <[email protected]> ${1700000000 + index} +0000\n` +
    `data 7\nhistory\n` +
    `M 100644 inline ${file}\ndata ${content.length}\n${content}\n` +
    `M 100644 inline ${other}\ndata ${otherContent.length}\n${otherContent}\n`;
}
runGit(origin, ["fast-import", "--quiet"], importInput);
runGit(origin, ["reset", "--hard", "HEAD"]);
runGit(origin, ["repack", "-adq"]);
runGit(fixtureRoot, [
  "clone",
  "--filter=blob:none",
  "--no-checkout",
  pathToFileURL(origin).href,
  seed,
]);

let sequence = 0;
async function makeReader() {
  const id = sequence++;
  const base = path.join(fixtureRoot, `base-${id}`);
  const linked = path.join(fixtureRoot, `reader-${id}`);
  await fsp.cp(seed, base, { recursive: true });
  runGit(base, ["config", "gc.auto", "0"]);
  runGit(base, ["config", "maintenance.auto", "false"]);
  runGit(base, ["worktree", "add", "--detach", linked]);
  const packDir = path.join(base, ".git", "objects", "pack");
  const packs = async () => (await fsp.readdir(packDir)).filter((name) => name.endsWith(".pack"));
  const initial = await packs();
  const newPacks = async () => (await packs()).filter((name) => !initial.includes(name));
  return { base, linked, newPacks };
}

function invoke(shim, args, options = {}) {
  const cwd = options.cwd || fixtureRoot;
  const env = {
    ...baseEnv,
    OPENCLAW_HOLD: "0",
    OPENCLAW_RM_DELAY: "0",
    ...options.env,
  };
  return new Promise((resolve) => {
    const child = spawn(shim, ["-C", cwd, ...args], {
      cwd: fixtureRoot,
      env,
      detached: process.platform !== "win32",
    });
    let stdout = "";
    let stderr = "";
    let timedOut = false;
    const timer = options.timeout
      ? setTimeout(() => {
          timedOut = true;
          try {
            process.kill(-child.pid, "SIGKILL");
          } catch {
            child.kill("SIGKILL");
          }
        }, options.timeout)
      : null;
    child.stdout.setEncoding("utf8").on("data", (chunk) => (stdout += chunk));
    child.stderr.setEncoding("utf8").on("data", (chunk) => (stderr += chunk));
    child.on("error", (error) => {
      if (timer) {
        clearTimeout(timer);
      }
      resolve({ code: null, signal: null, timedOut, stdout, stderr: String(error) });
    });
    child.on("close", (code, signal) => {
      if (timer) {
        clearTimeout(timer);
      }
      resolve({ code, signal, timedOut, stdout, stderr });
    });
  });
}

const bin = path.join(root, "bin");
await fsp.mkdir(bin);
const realGit = spawnSync("sh", ["-c", "command -v git"], { encoding: "utf8" }).stdout.trim();
const realRm = spawnSync("sh", ["-c", "command -v rm"], { encoding: "utf8" }).stdout.trim();
const journal = path.join(root, "journal");
await fsp.writeFile(journal, "");
await fsp.writeFile(
  path.join(bin, "git"),
  String.raw`#!/bin/sh
case " $* " in
  *" fetch "*)
    printf 'fetch-enter\n' >> "$OPENCLAW_JOURNAL"
    sleep "$OPENCLAW_HOLD"
    "$OPENCLAW_REAL_GIT" "$@"
    status=$?
    printf 'fetch-leave\n' >> "$OPENCLAW_JOURNAL"
    exit "$status" ;;
esac
exec "$OPENCLAW_REAL_GIT" "$@"
`,
  { mode: 0o755 },
);
await fsp.writeFile(
  path.join(bin, "rm"),
  String.raw`#!/bin/sh
case "$1 $2" in
  "-f "*"openclaw-history-blobs.lock/pid")
    sleep "$OPENCLAW_RM_DELAY" ;;
esac
exec "$OPENCLAW_REAL_RM" "$@"
`,
  { mode: 0o755 },
);

const wrapperEnv = {
  PATH: `${bin}${path.delimiter}${process.env.PATH ?? ""}`,
  OPENCLAW_JOURNAL: journal,
  OPENCLAW_REAL_GIT: realGit,
  OPENCLAW_REAL_RM: realRm,
};

async function readJournal() {
  const text = await fsp.readFile(journal, "utf8").catch(() => "");
  return text.trim().split("\n").filter(Boolean);
}
function maxOverlap(lines) {
  let current = 0;
  let maximum = 0;
  for (const line of lines) {
    if (line === "fetch-enter") {
      current += 1;
      maximum = Math.max(maximum, current);
    } else {
      current -= 1;
    }
  }
  return maximum;
}

// 1. Base shim: stale marker, two waiters. The delayed rm widens the real
// reclaim window so the successor's lock is removed while its fetch runs.
const baseRace = await makeReader();
const basePeer = path.join(fixtureRoot, `base-race-peer-${sequence}`);
runGit(baseRace.base, ["worktree", "add", "--detach", basePeer]);
const baseLegacy = path.join(baseRace.base, ".git", "openclaw-history-blobs.lock");
await fsp.mkdir(baseLegacy);
const deadPid = spawnSync("sh", ["-c", "echo $$"], { encoding: "utf8" }).stdout.trim();
await fsp.writeFile(path.join(baseLegacy, "pid"), `${deadPid}\n`);
await fsp.writeFile(journal, "");
const baseResults = await Promise.all([
  invoke(shims.base, ["log", "--stat", "--", file], {
    cwd: baseRace.linked,
    env: { ...wrapperEnv, OPENCLAW_HOLD: "6", OPENCLAW_RM_DELAY: "2" },
  }),
  invoke(shims.base, ["log", "--stat", "--", other], {
    cwd: basePeer,
    env: { ...wrapperEnv, OPENCLAW_HOLD: "6", OPENCLAW_RM_DELAY: "5" },
  }),
]);
const baseJournal = await readJournal();

// 2. Patched shim under the same stale marker and delayed rm. It ignores the
// dead pid, takes the kernel lock, and must serialise the same two readers.
const patchedRace = await makeReader();
const patchedPeer = path.join(fixtureRoot, `patched-race-peer-${sequence}`);
runGit(patchedRace.base, ["worktree", "add", "--detach", patchedPeer]);
const patchedLegacy = path.join(patchedRace.base, ".git", "openclaw-history-blobs.lock");
await fsp.mkdir(patchedLegacy);
const patchedDeadPid = spawnSync("sh", ["-c", "echo $$"], { encoding: "utf8" }).stdout.trim();
await fsp.writeFile(path.join(patchedLegacy, "pid"), `${patchedDeadPid}\n`);
await fsp.writeFile(journal, "");
const patchedResults = await Promise.all([
  invoke(shims.patched, ["log", "--stat", "--", file], {
    cwd: patchedRace.linked,
    env: { ...wrapperEnv, OPENCLAW_HOLD: "6", OPENCLAW_RM_DELAY: "2" },
  }),
  invoke(shims.patched, ["log", "--stat", "--", other], {
    cwd: patchedPeer,
    env: { ...wrapperEnv, OPENCLAW_HOLD: "6", OPENCLAW_RM_DELAY: "5" },
  }),
]);
const patchedJournal = await readJournal();

// 3. Patched shim: live legacy owner. The 300-iteration wait expires and the
// pickaxe search takes the offline budget path.
const patchedTimeout = await makeReader();
const livePid = spawn("sleep", ["600"], { stdio: "ignore" });
const patchedTimeoutLegacy = path.join(
  patchedTimeout.base,
  ".git",
  "openclaw-history-blobs.lock",
);
await fsp.mkdir(patchedTimeoutLegacy);
await fsp.writeFile(path.join(patchedTimeoutLegacy, "pid"), `${livePid.pid}\n`);
await fsp.writeFile(journal, "");
const patchedStarted = Date.now();
const patchedTimeoutResult = await invoke(
  shims.patched,
  ["log", "-S", "history line 3", "--", file],
  { cwd: patchedTimeout.linked, env: wrapperEnv },
);
const patchedElapsed = Date.now() - patchedStarted;
const patchedTimeoutJournal = await readJournal();
const patchedPacks = await patchedTimeout.newPacks();
livePid.kill();

// 4. Base shim: the same live marker. The old code resets its attempt counter
// while kill -0 succeeds, so a hard timeout is the only way out.
const baseTimeout = await makeReader();
const livePidTwo = spawn("sleep", ["600"], { stdio: "ignore" });
const baseTimeoutLegacy = path.join(baseTimeout.base, ".git", "openclaw-history-blobs.lock");
await fsp.mkdir(baseTimeoutLegacy);
await fsp.writeFile(path.join(baseTimeoutLegacy, "pid"), `${livePidTwo.pid}\n`);
await fsp.writeFile(journal, "");
const baseStarted = Date.now();
const baseTimeoutResult = await invoke(shims.base, ["log", "-S", "history line 3", "--", file], {
  cwd: baseTimeout.linked,
  env: wrapperEnv,
  timeout: 45_000,
});
const baseElapsed = Date.now() - baseStarted;
const baseTimeoutJournal = await readJournal();
livePidTwo.kill();

console.log(
  `[base-reclaim-race] maxFetchOverlap=${maxOverlap(baseJournal)} events=${baseJournal.join(",")}`,
);
console.log(
  `[patched-reclaim] maxFetchOverlap=${maxOverlap(patchedJournal)} events=${patchedJournal.join(",")}`,
);
console.log(
  `[patched-legacy-timeout] elapsedMs=${patchedElapsed} code=${patchedTimeoutResult.code} newPacks=${patchedPacks.length} stderr=${patchedTimeoutResult.stderr.includes("shared partial-clone blob budget") ? "budget-error" : "missing-budget-error"}`,
);
console.log(
  `[base-legacy-timeout] elapsedMs=${baseElapsed} timedOut=${baseTimeoutResult.timedOut} signal=${baseTimeoutResult.signal}`,
);

const failures = [];
if (maxOverlap(baseJournal) < 2) {
  failures.push("base reclaim race did not overlap");
}
if (maxOverlap(patchedJournal) !== 1) {
  failures.push("patched reclaim race did not serialise");
}
if (patchedTimeoutResult.code !== 2) {
  failures.push("patched legacy timeout did not exit 2");
}
if (!patchedTimeoutResult.stderr.includes("shared partial-clone blob budget")) {
  failures.push("patched legacy timeout did not print the budget error");
}
if (patchedPacks.length !== 0) {
  failures.push("patched legacy timeout created packs");
}
if (!baseTimeoutResult.timedOut) {
  failures.push("base legacy timeout returned instead of hanging");
}
if (failures.length > 0) {
  console.error(`[proof-failures] ${failures.join("; ")}`);
  process.exitCode = 1;
}

@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added size: S triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Nov 16, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 16, 2026
@clawsweeper

clawsweeper Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This PR replaces reclaimable directory locking for shared Git history prefetches with kernel locking, a directory fallback, and a bounded legacy-owner wait.

Example: Two linked worktrees run git log --stat against different cold historical files while a stale legacy lock marker exists.

  • Before: The supplied base trace shows fetch-enter, fetch-enter, fetch-leave, fetch-leave.
  • After: The supplied Linux kernel-lock trace shows fetch-enter, fetch-leave, fetch-enter, fetch-leave.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The revised evidence clears the previous proof gap, but the independent fallback mutex leaves a concrete serialization defect and an unresolved portability decision.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (terminal): The supplied Ubuntu terminal trace exercises the actual generated Git shim and real Git file transport across linked worktrees, showing serialized fetch boundaries after the fix and offline failure after the legacy timeout; native macOS and FreeBSD execution remain disclosed limitations.
Patch quality 🦪 silver shellfish (2/6) 1 actionable review finding remain.

Product

Kind: Bug fix · Worth it: Needs a maintainer decision · Fix scope: Complete
User problem: Concurrent agent history reads can overlap blob downloads, while a reused PID in a stale marker can block searches indefinitely.
Reason: The central repair has clear value, but the newly introduced fallback changes established crash-recovery behavior without an owner decision.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep this PR open: the earlier timeout finding is resolved and the Linux runtime evidence is sufficient, but the kernel and fallback mutexes can admit concurrent fetches into the same object store.

Priority: P2
Reviewed head: a097faec605e25d9fdd1325e5520294f4925d5d4
Owner decision: Required. See Decision needed.

Decision needed

  • Question: Should systems without usable flock or lockf retain prefetch through a portable mutex, or may they stop prefetching with actionable recovery guidance?
  • Recommendation: Preserve portable prefetch: Have the contributor revise locking so supported environments share one exclusion protocol and retain a usable recovery path.
  • Why: The proposed fallback changes dead-owner recovery from automatic reclamation to permanent manual cleanup, and no recorded owner decision accepts that operational change.

Before merge

  • Make kernel and fallback callers share one exclusion protocol (P2) - When two environments share a git-common-dir but only one has usable descriptor locking, one caller acquires .lock.kernel while the other acquires .lock.fallback. Both then recheck and fetch independently, so concurrent cold history reads can overlap downloads into the same object store. The PR body explicitly identifies the host/container case, and the fallback tests establish that missing flock is supported. The previous common directory mutex coordinated both environments. Use an interoperable mutex for both paths, or obtain approval to skip prefetch with actionable guidance when kernel locking is unavailable.

Findings

  • [P2] Make kernel and fallback callers share one exclusion protocol — src/infra/agent-git-shim.ts:427-430
Agent review details

How this fits together

The agent Git PATH shim discovers missing historical blobs in shared partial clones, coordinates their prefetch, and then executes the requested Git command with the existing offline-search policy.

flowchart TD
  A[Agent Git command] --> B[Git PATH shim]
  B --> C[Discover missing blobs]
  C --> D[Wait for legacy owner]
  D --> E[Acquire prefetch mutex]
  E --> F[Recheck and fetch blobs]
  F --> G[Execute requested Git command]
Loading

Technical review

Best possible solution:

Keep serialization in the existing prefetch owner with one interoperable mutex and an owner-approved recovery contract for systems lacking descriptor-lock support.

Do we have a high-confidence way to reproduce the issue?

The supplied real-Git trace demonstrates the original reclaim overlap and corrected Linux serialization; source inspection independently establishes that mixed kernel and fallback callers remain mutually uncoordinated.

Is this the best way to solve the issue?

Kernel locking removes the reclaim race within the existing owner, but an independently named directory fallback defeats shared serialization when callers have different locking-tool availability.

Full review comments:

  • [P2] Make kernel and fallback callers share one exclusion protocol — src/infra/agent-git-shim.ts:427-430
    When two environments share a git-common-dir but only one has usable descriptor locking, one caller acquires .lock.kernel while the other acquires .lock.fallback. Both then recheck and fetch independently, so concurrent cold history reads can overlap downloads into the same object store. The PR body explicitly identifies the host/container case, and the fallback tests establish that missing flock is supported. The previous common directory mutex coordinated both environments. Use an interoperable mutex for both paths, or obtain approval to skip prefetch with actionable guidance when kernel locking is unavailable.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.96

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 6ad60f571591.

Provenance checked

  • Shared history-prefetch serialization keeps the original intent (a07cbf5: Coalesce overlapping historical reads under one common-directory lock and recheck missing objects before fetching.)
  • Live-owner waiting changes intended behavior with a stated reason (4092d35: Live batches can exceed the ordinary wait bound; readers must not begin parallel lazy fetching.)
  • Offline execution after unsuccessful preparation keeps the original intent (ff0a22c: Prevent failed or incomplete prefetch from falling through to unbounded native lazy fetching.)
  • Dead-owner reclamation changes intended behavior with a stated reason (a07cbf5: Recover the prefetch mutex after its owning shell is killed; this PR deliberately removes reclamation to avoid deleting a successor's lock.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced locking change: The pinned introduced diff replaces the existing directory protocol with a kernel mutex and an independently named fallback mutex. (src/infra/agent-git-shim.ts:403, a097faec605e)
  • Independent mutexes: Kernel callers lock openclaw-history-blobs.lock.kernel, while fallback callers acquire openclaw-history-blobs.lock.fallback; neither path participates in the other's mutex, and both invoke fetch_blobs. (src/infra/agent-git-shim.ts:429, a097faec605e)
  • Previous finding resolved: The bounded legacy wait now precedes mutex acquisition, while prepared_blobs is assigned before preparation; timeout therefore preserves offline execution for recognized non-show content searches. (src/infra/agent-git-shim.ts:472, a097faec605e)
  • Supplied real behavior proof: The full PR body supplies a symmetric base-versus-patched fetch journal using the real shim, Git subprocesses, linked worktrees, and a local file transport; it also records patched legacy timeout with exit 2, zero new packs, and budget guidance. (a097faec605e)
  • Current-main behavior and provenance: Fetched main retains the directory mutex. The original history-prefetch change introduced shared serialization, and fix: batch content searches across shared Git history #197448 deliberately retained waiting for live owners to prevent parallel lazy fetching. (src/infra/agent-git-shim.ts:452, 6ad60f571591)
  • Fallback recovery change: The PR explicitly documents that a killed fallback owner leaves a permanent marker requiring manual removal, and the added orphan-marker test expects subsequent searches to fail without fetching. (src/infra/agent-git-shim.history.test.ts:799, a097faec605e)

PR surface

Source +41, Tests +386. Total +427 across 2 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 64 23 +41
Tests 1 386 0 +386
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 450 23 +427

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded reliability repair for concurrent Git history reads in shared partial clones.
  • merge-risk: 🚨 compatibility: Fallback-only environments lose automatic dead-owner recovery and can require manual lock removal after interruption.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🐚 platinum hermit and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (1 earlier review cycle)
  • reviewed 2026-11-16T05:30:38.634Z sha f2dd84f :: needs real behavior proof before merge. :: [P2] Keep legacy-lock timeout from starting parallel lazy fetches

Reviewed November 17, 2026, 12:39 PM ET / 17:39 UTC (Revision 2).

The git shim serialised lazy history hydration with a mkdir directory lock, an
owner pid file, a thirty-second attempt bound and a kill-based reclaim. That
protocol unlinks and re-creates the lock: a waiter that decides an owner is dead
removes the record and the directory, so it can remove the lock a successor has
just created and two callers can then fetch into one object store at the same
time.

Replace the protocol with a kernel lock on a file the shim never unlinks:
flock(1) on the open descriptor on Linux, lockf(1) elsewhere. With no unlink
there is no reclaim step and no interval in which two callers both believe they
own the lock. A directory marker left by an older shim is still read so an
in-place upgrade keeps its ordering; a stale record is ignored, never reclaimed.

Test: six linked worktrees race two disjoint object sets through a wrapper that
journals fetch boundaries, and the journal must alternate enter and leave.
kill -0 only shows that a pid exists, never that it is still an old shim. A
leftover pid record whose pid was reused by a long-lived process of the same
user made every content search spin on the marker for good. The previous
candidate kept the wait after the kernel lock, so N callers queued for k x 30 s.

Move the bounded wait before the kernel lock so parallel callers time out
together, and give the prefetch up when it expires: non-show content searches
take the failed-preparation path, running offline with the budget error instead
of starting a competing lazy fetch beside the old owner. Show keeps its
speculative native fallback.

Run the kernel open and lock in a nested subshell so a failed exec falls back
instead of ending the prefetch. Keep a portable mkdir mutex, without the old
reclaim step, for systems where flock or the lockf descriptor form is
unavailable. Cleanup only removes the record while the process still owns the
pid file. The fallback directory lives in the git-common-dir, not in a linked
worktree's .git file. If the owner is killed before cleanup, stop every process
that may use it and remove it with
rm -r "$(git rev-parse --git-common-dir)/openclaw-history-blobs.lock.fallback".
The kernel lock and this mutex are different paths, so environments that resolve
different binaries do not exclude each other.

Test: a legacy marker holding a live pid must return, a marker that disappears
before the bound must release the wait and fetch, a stale marker with a delayed
reclaim must serialise two readers, a failed or missing flock must fall back,
two fallback readers must serialise and remove the marker, and an orphaned
fallback marker must expire without removing it. The timeout tests drive the
300-iteration wait through a fake sleep wrapper instead of real 30 s waits; the
real 30 s and 45 s measurements stay in the proof script.
@Szqub
Szqub force-pushed the fix/kernel-history-blobs-lock branch from f2dd84f to a097fae Compare November 17, 2026 17:31
@Szqub

Szqub commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Nov 17, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Nov 17, 2026
@Szqub

Szqub commented Nov 22, 2026

Copy link
Copy Markdown
Contributor Author

Could a maintainer clarify two compatibility requirements before I revise the lock?

  1. Must bounded bulk blob prefetch remain available for cold log -S/-G/--stat, blame, diff, and revision-scoped grep on every supported platform? I propose removing .lock.fallback: it can admit a fetch alongside a kernel-lock holder and can leave a permanent directory when its owner dies. Bulk prefetch would require explicit enablement for a verified store, initially Linux with util-linux flock on a local filesystem where all participating readers share the kernel and lock inode. The default elsewhere would be to skip bulk prefetch. On macOS, FreeBSD, images without a working lock, and unverified NFS/CIFS or mixed backends, a cold search needing missing blobs would then typically exit 2 with the existing budget guidance. An operator could prepare the required objects explicitly or move the workload to a supported locking setup. Warm reads would still work, including grep exit 1 for no match. Missing-commit preparation would be preserved. On an unverified store, show rev:path would also skip bulk prefetch and retain native lazy fetching for individual objects. Unrecognized command forms would keep their existing native behavior.
  2. Must old main/beta shims and new shims support cold bulk prefetch against one store during rolling upgrades? The shim source is absent at v2026.11.6 and present at v2026.11.10-beta.1. An old reader can start after the marker check. I propose keeping bulk disabled for new readers until old readers and their fetch children have drained and old shims can no longer start, then enabling it explicitly. Separate object stores would allow both versions to prefetch during the transition. Would those limits be acceptable?

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. size: M status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant