Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync lanes): a refused member's lane group republishes its held siblings instead of requeueing them

garrytan0c8746f8acfb
diff --git a/src/core/persistence/group-publish.ts b/src/core/persistence/group-publish.ts
index 7b21053d00..719db0336a 100644
--- a/src/core/persistence/group-publish.ts
+++ b/src/core/persistence/group-publish.ts
@@ -469,23 +469,30 @@ async function laneFallback(engine: BrainEngine, rows: WriteRequest[], reason: G
/**
* #6712 lanes: a lane group rolled back because one sync member's own check refused it (a file edited after admission,
- * an identity or origin refusal). That page takes its fate now, from the same refusal the single path would read again,
- * and the other members go back to the queue to publish as a group: on a lane root the single path's exclusive lock
- * waits behind the lanes, so publishing them one at a time here never gets the worktree. False when the member is no
- * longer this pass's to settle (its claim moved, or a recovery record holds it).
+ * an identity or origin refusal). That page takes its fate now, from the same refusal the single path would read again
+ * (`settled`), and the caller publishes the other members again as a lane group under the claims it still holds: on a
+ * lane root the single path's exclusive lock waits behind the lanes, and sending them back to the queue would make
+ * every later lane group waiting on this one's turn yield too (`predecessor_requeued`). `requeued` when the refusal
+ * sent the member back to the queue (a transient database failure: nothing after it may overtake it) or another
+ * member's claim already went back (a file restoration): the members still held are released behind it. False when the member is no longer this pass's to settle (its claim moved, or a recovery
+ * record holds it).
*/
-async function settleCulprit(engine: BrainEngine, rows: WriteRequest[], culprit: NonNullable<GroupPublication['culprit']>, run: GroupExecution): Promise<boolean> {
+async function settleCulprit(engine: BrainEngine, rows: WriteRequest[], culprit: NonNullable<GroupPublication['culprit']>, run: GroupExecution): Promise<'settled' | 'requeued' | false> {
const row = rows[culprit.index];
if (!row || !syncMember(row) || (culprit.error as { code?: string }).code === 'unexpected_file_bytes') return false;
const current = await getWriteRequestById(engine, row.id);
if (!current || current.state !== 'running' || current.execution_token !== row.execution_token || current.recovery) return false;
- run.settled(await finishUnpublishedFailure(engine, current, culprit.error, 'publication'));
+ const done = await finishUnpublishedFailure(engine, current, culprit.error, 'publication');
+ run.settled(done);
+ const others: Array<{ other: WriteRequest; held: boolean }> = [];
for (const other of rows) {
if (other.id === row.id) continue;
const live = await getWriteRequestById(engine, other.id);
- if (live?.state === 'running' && live.execution_token === other.execution_token) await releaseUnpublishedClaim(engine, other, 'group_member_waiting');
+ others.push({ other, held: live?.state === 'running' && live.execution_token === other.execution_token });
}
- return true;
+ if (['committed', 'conflict', 'failed', 'cancelled'].includes(done.state) && others.every(({ held }) => held)) return 'settled';
+ for (const { other, held } of others) if (held) await releaseUnpublishedClaim(engine, other, 'group_member_waiting');
+ return 'requeued';
}
/**
@@ -720,19 +727,32 @@ export async function executeClaimedGroup(engine: BrainEngine, rows: WriteReques
if (run.publication) await holdClaimForPublication(lease, () => renewGroupClaims(engine, liveRows, publicationLeaseMs(run.publication!.ceilingMs), undefined,
live.map(({ i }) => stampOf(i))));
let requeued = new Set<string>();
+ // #6712 lanes: the members a member's own refusal left publish again as a group, at most once per member.
+ let publishing = live;
if (live.every(({ i }) => 'ok' in prepared[i]!)) {
- // #6278 lanes: a prefix publishes under the original group's order key, then drops its own begun mark.
- const markOriginal = run.lane && liveRows.length < rows.length ? await awaitLaneBegin(run.lane, rows) : null;
- const hooks = markOriginal ? { ...run.hooks, began: () => { markOriginal(); run.hooks?.began?.(); } } : run.hooks;
- const result = await bounded(() => publishGroup(engine, liveRows, live.map(({ i }) => (prepared[i] as { ok: PreparedMutation }).ok), run.hostId, hooks, run.lane ?? null));
- if (run.lane && liveRows.length < rows.length) run.lane.begun.delete(liveRows.at(-1)!.request_id);
- if (result.done) { for (const row of result.done) run.settled(row); return true; }
- requeued = new Set(result.requeued);
- if (run.lane && result.culprit && await settleCulprit(engine, liveRows, result.culprit, run)) return true;
- if (run.lane && await laneFallback(engine, liveRows, result.reason, run) !== null) return progressed;
+ for (;;) {
+ const publishRows = publishing.map(({ row }) => row);
+ // #6278 lanes: a prefix publishes under the original group's order key, then drops its own begun mark.
+ const markOriginal = run.lane && publishRows.length < rows.length ? await awaitLaneBegin(run.lane, rows) : null;
+ const hooks = markOriginal ? { ...run.hooks, began: () => { markOriginal(); run.hooks?.began?.(); } } : run.hooks;
+ const result = await bounded(() => publishGroup(engine, publishRows, publishing.map(({ i }) => (prepared[i] as { ok: PreparedMutation }).ok), run.hostId, hooks, run.lane ?? null));
+ if (run.lane && publishRows.length < rows.length) run.lane.begun.delete(publishRows.at(-1)!.request_id);
+ if (result.done) { for (const row of result.done) run.settled(row); return true; }
+ requeued = new Set(result.requeued);
+ const culprit = run.lane && result.culprit ? await settleCulprit(engine, publishRows, result.culprit, run) : false;
+ if (culprit === 'requeued') return true;
+ if (culprit === 'settled') {
+ progressed = true;
+ publishing = publishing.filter((_, k) => k !== result.culprit!.index);
+ if (!publishing.length) return true;
+ continue;
+ }
+ if (run.lane && await laneFallback(engine, publishRows, result.reason, run) !== null) return progressed;
+ break;
+ }
} else if (run.lane && await laneFallback(engine, liveRows, 'failed', run) !== null) return progressed;
let release = false;
- for (const { row: member, i } of live) {
+ for (const { row: member, i } of publishing) {
let row = member;
let current = await getWriteRequestById(engine, row.id);
// A claim the group's file restoration released is taken back, in order, while this pass still owns the worktree.
diff --git a/test/managed-sync-lanes.test.ts b/test/managed-sync-lanes.test.ts
index 65c1f2837d..ce1976a65c 100644
--- a/test/managed-sync-lanes.test.ts
+++ b/test/managed-sync-lanes.test.ts
@@ -330,16 +330,44 @@ test('a page edited after its freeze fails alone inside a lane group; the group
for (let i = 0; i < 40; i++) writeFileSync(join(f.root, `notes/n${pad(i)}.md`), revised(i, 'revised'));
git(f.root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qam', 'revise');
const edited = 'notes/n013.md';
+ // The edited page's group is held in preparation until a later lane group has applied and waits for its turn behind it,
+ // so the refusal always lands while that group waits (the window CI hit only under load: the group sent back to the
+ // queue made every lane group waiting behind it yield, `predecessor_requeued`, and count as a fallback).
+ const requestRow = async (requestId: string | undefined) => (await engine!.executeRaw<{ slug: string; idx: number }>(
+ "SELECT slug, (intent->>'index')::int AS idx FROM persistence_requests WHERE request_id=$1::uuid", [requestId ?? null]))[0];
+ let behind: () => void = () => {};
+ const laterGroupWaiting = new Promise<void>(resolve => { behind = resolve; });
+ let waited = false, reached = false;
installFaultHook(async (point, detail) => {
if (point === 'sync:after_freeze' && detail.sourceId === f.id && detail.path === edited) writeFileSync(join(f.root, edited), revised(13, 'uncommitted'));
+ if (detail.sourceId !== f.id || !detail.requestId) return;
+ if (point === 'lane:applied' && ((await requestRow(detail.requestId))?.idx ?? -1) > 13) { reached = true; behind(); }
+ if (point === 'consumer:preparing' && !waited && (await requestRow(detail.requestId))?.slug === 'notes/n013') {
+ waited = true;
+ await Promise.race([laterGroupWaiting, new Promise(resolve => setTimeout(resolve, 20_000))]);
+ }
});
+ // Every claim of this source that goes back to the queue, and why.
+ await engine.executeRaw(`CREATE TABLE lane_requeues(slug text, reason text);
+ CREATE FUNCTION lane_requeue_log() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN
+ INSERT INTO lane_requeues VALUES (NEW.slug, NEW.blocked_reason); RETURN NEW; END $$;
+ CREATE TRIGGER lane_requeue_log AFTER UPDATE ON persistence_requests FOR EACH ROW
+ WHEN (OLD.state = 'running' AND NEW.state = 'queued' AND NEW.source_id = '${f.id}') EXECUTE FUNCTION lane_requeue_log()`);
const stop = new AbortController(), timer = setTimeout(() => stop.abort(), 90_000);
- let result;
- try { result = await performSync(engine, { ...opts, signal: stop.signal }); }
- finally { clearTimeout(timer); installFaultHook(undefined); }
+ let result, requeues: Array<{ slug: string; reason: string | null }> = [];
+ try {
+ result = await performSync(engine, { ...opts, signal: stop.signal });
+ requeues = await engine.executeRaw('SELECT slug, reason FROM lane_requeues ORDER BY slug');
+ } finally {
+ clearTimeout(timer); installFaultHook(undefined);
+ await engine.executeRaw('DROP TRIGGER lane_requeue_log ON persistence_requests; DROP FUNCTION lane_requeue_log(); DROP TABLE lane_requeues');
+ }
expect(stop.signal.aborted).toBe(false);
+ expect(waited && reached).toBe(true);
+ // The refused page's group keeps its other members' claims and publishes them; none goes back to the queue.
+ expect(requeues).toEqual([]);
expect(result.drain?.outcome).not.toBe('blocked');
- // The refused page never sends its group to the single path (a lane fallback), which waits behind the lanes.
+ // The refused page never sends its group to the single path or back to the queue (a lane fallback each).
expect(result.drain?.bulk?.lanes.fallbacks).toBe(0);
const status = await readSyncStatus(engine, f.id);
expect(status.holds.map(hold => `${hold.code}:${hold.path}`)).toEqual([`worktree_dirty:${edited}`]);