Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

#6712 PR 4b: a prior pass's open import is the resumed pass's import

garrytan22b346174dc9
diff --git a/src/core/persistence/sync-pass-carried.ts b/src/core/persistence/sync-pass-carried.ts
new file mode 100644
index 0000000000..6a33333623
--- /dev/null
+++ b/src/core/persistence/sync-pass-carried.ts
@@ -0,0 +1,39 @@
+/**
+ * #6712 PR 4b: a pass's page requests that outlive it. A pass that stops while its imports or deletions are still open
+ * (`writer_pending`, a timeout, a block) records them in the pass row (`obligations.pending_requests`, at most
+ * `OPEN_AT_STAMP_CAP`, with the earlier passes' still open). The next pass reports each one that committed as its own
+ * import, whoever published it and whenever (before the pass, or during it before its level read saw the path open), as the
+ * cursor engine counted a pending write it resumed. A request still open at the pass's first triage names an in-flight path,
+ * so the pass waits on it (sync-pass-run.ts `awaitInFlight`) and counts it there; each id is counted once and then dropped.
+ */
+import type { BrainEngine } from '../engine.ts';
+import { OPEN_AT_STAMP_CAP } from './sync-pass-row.ts';
+
+export type CarriedCounts = { added: number; modified: number; deleted: number; renamed: number; chunks: number };
+
+/** The page requests to carry past a stop: this pass's still open, and the carried ones still open. */
+export async function openPassRequests(engine: Pick<BrainEngine, 'executeRaw'>, input: { sourceId: string; passId: string; carried: readonly string[] }): Promise<string[]> {
+ const rows = await engine.executeRaw<{ id: string }>(`SELECT id::text AS id FROM persistence_requests WHERE source_id=$1 AND state IN ('queued','running','recovering')
+ AND intent->>'kind' IN ('managed_sync_import','managed_sync_delete') AND (intent->>'passId'=$2 OR id=ANY($3::uuid[])) ORDER BY sequence LIMIT $4`,
+ [input.sourceId, input.passId, [...input.carried], OPEN_AT_STAMP_CAP]);
+ return rows.map(row => row.id);
+}
+
+/** Of the carried `ids`: the committed ones counted as the drain counts a commit (sync-run.ts `countCommitted`), and those still open. */
+export async function settleCarried(engine: Pick<BrainEngine, 'executeRaw'>, ids: readonly string[]): Promise<{ counts: CarriedCounts; open: string[] }> {
+ const counts: CarriedCounts = { added: 0, modified: 0, deleted: 0, renamed: 0, chunks: 0 }, open: string[] = [];
+ const rows = await engine.executeRaw<{ id: string; state: string; kind: string | null; renamed: boolean; status: string | null; noop: boolean; chunks: number | null }>(
+ `SELECT id::text AS id, state, intent->>'kind' AS kind, intent ? 'renameFrom' AS renamed, outcome->>'status' AS status,
+ COALESCE((outcome->>'noop')::boolean, false) AS noop, (outcome->>'chunks')::int AS chunks FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY sequence`, [[...ids]]);
+ for (const row of rows) {
+ if (['queued', 'running', 'recovering'].includes(row.state)) { open.push(row.id); continue; }
+ if (row.state !== 'committed') continue;
+ counts.chunks += Number(row.chunks ?? 0);
+ if (row.noop) continue;
+ if (row.kind === 'managed_sync_delete') counts.deleted++;
+ else if (row.renamed) counts.renamed++;
+ else if (row.status === 'created') counts.added++;
+ else counts.modified++;
+ }
+ return { counts, open };
+}
diff --git a/src/core/persistence/sync-pass-row.ts b/src/core/persistence/sync-pass-row.ts
index b82e2cc233..909043c1e0 100644
--- a/src/core/persistence/sync-pass-row.ts
+++ b/src/core/persistence/sync-pass-row.ts
@@ -88,6 +88,8 @@ export interface ManagedSyncPassValue {
* (`gbrain repair managed-sync-orphans`, `slug_mode_refused`).
*/
slug_mode?: 'git-root' | 'source-root';
+ /** #6712 PR 4b: the page requests (row ids) passes left open when they stopped; the next pass reports each that commits as its import (sync-pass-carried.ts). */
+ pending_requests?: string[];
/** #6712 PR 3 (L7) on the pass: the page request a blocked pass stopped on, which the next pass replays while what refused it is unchanged. */
blocked?: { request_id: string; pass_id: string };
};
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index 1e702e75a4..b9d69935b6 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -33,6 +33,7 @@ import { readSyncAdmission, type SyncAdmission } from './sync-admission.ts';
import { faultPoint } from './fault-points.ts';
import { passFoldBase, passIdleProbe, readShadowLevel, workingIdleChange, type PassLevelCache, type ShadowLevel, type ShadowPath } from './sync-pass.ts';
import { ownWritebackCommit, type PassFold } from './sync-pass-fold.ts';
+import { openPassRequests, settleCarried } from './sync-pass-carried.ts';
import { loopYield } from './sync-yield.ts';
import { recallWorkingStatCache, rememberWorkingStatCache, SyncTreeReadIncomplete } from './sync-git-stream.ts';
import { syncPassKind } from './sync-classify.ts';
@@ -268,12 +269,14 @@ async function batchEntries(engine: BrainEngine, level: ShadowLevel, deletes: Sh
* Waits (bounded) until no open request or Git effect of the worktree names one of the in-flight pages or origins, and
* returns what the requests open at its start committed meanwhile: an earlier drain's work this pass reports as its own.
*/
-async function awaitInFlight(engine: BrainEngine, level: ShadowLevel, inFlight: ShadowPath[], budgetMs: number, assertActive: () => void): Promise<{ added: number; modified: number; deleted: number; renamed: number }> {
+async function awaitInFlight(engine: BrainEngine, level: ShadowLevel, inFlight: ShadowPath[], budgetMs: number, assertActive: () => void,
+ /** Earlier passes' open requests (sync-pass-carried.ts): counted here when they commit, even after the open read below. */
+ carried: readonly string[] = []): Promise<{ added: number; modified: number; deleted: number; renamed: number; committed: string[] }> {
const pageIds = inFlight.flatMap(entry => entry.pageId === null ? [] : [entry.pageId]);
const origins = inFlight.map(entry => entryPaths(level, entry.path).sourcePath);
const names = `r.page_id=ANY($2::int[]) OR r.intent->>'sourcePath'=ANY($3::text[]) OR r.intent->>'path'=ANY($3::text[])`;
- const opened = await engine.executeRaw<{ id: string }>(`SELECT r.id FROM persistence_requests r WHERE r.source_id=$1 AND r.state IN ('queued','running','recovering') AND (${names})`,
- [level.sourceId, pageIds, origins]);
+ const opened = [...new Set([...(await engine.executeRaw<{ id: string }>(`SELECT r.id FROM persistence_requests r WHERE r.source_id=$1 AND r.state IN ('queued','running','recovering') AND (${names})`,
+ [level.sourceId, pageIds, origins])).map(row => String(row.id)), ...carried])];
const until = Date.now() + budgetMs;
while (Date.now() < until) {
// The open work readOpenWork marked: an open request, or a pending Git effect named by its request or its relative_path
@@ -285,11 +288,12 @@ async function awaitInFlight(engine: BrainEngine, level: ShadowLevel, inFlight:
if (!open) break;
await new Promise(resolve => setTimeout(resolve, 100));
}
- const credited = { added: 0, modified: 0, deleted: 0, renamed: 0 };
+ const credited = { added: 0, modified: 0, deleted: 0, renamed: 0, committed: [] as string[] };
if (!opened.length) return credited;
const created = new Set(inFlight.filter(entry => entry.pageId === null).map(entry => entryPaths(level, entry.path).sourcePath));
- const committed = await engine.executeRaw<{ kind: string | null; source_path: string | null; renamed: boolean }>(`SELECT intent->>'kind' AS kind, intent->>'sourcePath' AS source_path,
- intent ? 'renameFrom' AS renamed FROM persistence_requests WHERE id=ANY($1::uuid[]) AND state='committed'`, [opened.map(row => row.id)]);
+ const committed = await engine.executeRaw<{ id: string; kind: string | null; source_path: string | null; renamed: boolean }>(`SELECT id::text AS id, intent->>'kind' AS kind, intent->>'sourcePath' AS source_path,
+ intent ? 'renameFrom' AS renamed FROM persistence_requests WHERE id=ANY($1::uuid[]) AND state='committed'`, [opened]);
+ credited.committed = committed.map(row => row.id);
for (const row of committed) {
if (row.kind === 'managed_sync_delete') credited.deleted++;
else if (row.kind !== 'managed_sync_import') continue;
@@ -658,6 +662,10 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
const save = async (outcome: PassOutcome, stopReason: string | null, pin = false) => {
const ended = outcome !== 'open';
+ if (ended && outcome !== 'synced') {
+ const open = await openPassRequests(engine, { sourceId, passId, carried: value.obligations.pending_requests ?? [] });
+ if (open.length) value.obligations.pending_requests = open; else delete value.obligations.pending_requests;
+ }
value.telemetry = { ...value.telemetry, outcome, stop_reason: stopReason, settled: S.size + yieldSettled, counts: { ...counts, ...passApplyCounts(applied) },
classes: applied.classes, ...(applied.summary ? { summary: applied.summary } : {}),
...(ended ? { ended_at: new Date().toISOString(), duration_ms: Date.now() - started } : {}) };
@@ -782,6 +790,13 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
if (applied.sweptAll && !value.obligations.legacy_sweep) value.obligations.legacy_sweep = { first_full_at: new Date().toISOString() };
if (!remote) value.obligations.deletes_withheld = applied.withheld?.set_hash ?? null;
const { deletes, imports, inFlight, mismatch, owed } = await triageRound(level, { S, legacyWaived, readmitted, admission, remote, counts });
+ // Earlier passes' requests that committed since they stopped are this pass's imports (sync-pass-carried.ts).
+ if (value.obligations.pending_requests?.length) {
+ const carried = await settleCarried(engine, value.obligations.pending_requests);
+ addCounts(counts, carried.counts);
+ sliceBase.pages += carried.counts.added + carried.counts.modified + carried.counts.renamed;
+ if (carried.open.length) value.obligations.pending_requests = carried.open; else delete value.obligations.pending_requests;
+ }
lastMismatch = mismatch;
const candidates = deletes.length + imports.length;
if (round === 1) candidatesFirst = candidates + inFlight.length + owed.length;
@@ -791,8 +806,10 @@ export async function runSyncPass(engine: BrainEngine, input: SyncPassInput): Pr
if (!candidates && inFlight.length && waits < IN_FLIGHT_WAITS) {
waits++; round--;
startPersistenceConsumer(engine, loadConfig() ?? { engine: engine.kind }).wake(true);
- const credited = await awaitInFlight(engine, level, inFlight, opts.drainStartedAt ? 30_000 : 5_000, assertActive);
+ const credited = await awaitInFlight(engine, level, inFlight, opts.drainStartedAt ? 30_000 : 5_000, assertActive, value.obligations.pending_requests);
Object.assign(counts, { added: counts.added + credited.added, modified: counts.modified + credited.modified, deleted: counts.deleted + credited.deleted, renamed: counts.renamed + credited.renamed });
+ const carried = value.obligations.pending_requests?.filter(id => !credited.committed.includes(id));
+ if (carried?.length) value.obligations.pending_requests = carried; else delete value.obligations.pending_requests;
sliceBase.pages += credited.added + credited.modified + credited.renamed;
continue;
}
diff --git a/test/e2e/sync-pass-carried-6712-postgres.test.ts b/test/e2e/sync-pass-carried-6712-postgres.test.ts
new file mode 100644
index 0000000000..11556bca43
--- /dev/null
+++ b/test/e2e/sync-pass-carried-6712-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../sync-pass-carried-6712.test.ts'));
diff --git a/test/sync-pass-carried-6712.test.ts b/test/sync-pass-carried-6712.test.ts
new file mode 100644
index 0000000000..9772f42985
--- /dev/null
+++ b/test/sync-pass-carried-6712.test.ts
@@ -0,0 +1,83 @@
+/**
+ * #6712 PR 4b: a page request a pass leaves open when it stops (`writer_pending`) is the next pass's import, whoever commits it
+ * and whenever (sync-pass-carried.ts). The pass row carries the open request ids (`obligations.pending_requests`); the next
+ * pass counts each one that committed once, then drops it.
+ *
+ * Protects (the race behind test/persistence-managed-sync.test.ts 'pending durable sync retries'):
+ * - the request commits before the resumed pass's level read: the level sees the page settled, and the pass still reports
+ * it as its import (`first_sync`, added 1);
+ * - the request commits after the level read saw it in flight but before the pass waits on it: counted once, not twice;
+ * - the pass waits on it and counts it itself: counted once;
+ * - every case leaves no carried id behind, and a following pass is up to date.
+ *
+ * Fault hooks pick the commit point, so no case depends on machine load. PGLite here; Postgres through
+ * test/e2e/sync-pass-carried-6712-postgres.test.ts.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import { execFileSync } from 'node:child_process';
+import { writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { type FaultPoint, installFaultHook } from '../src/core/persistence/fault-points.ts';
+import { acquireWorktree, getWorktreeBinding } from '../src/core/persistence/ownership.ts';
+import { disposePersistenceConsumer, startPersistenceConsumer } from '../src/core/persistence/service.ts';
+import { MANAGED_SYNC_PASS_OP } from '../src/core/persistence/sync-pass-row.ts';
+import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { managedBrain } from './helpers/managed-brain.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { waitFor } from './helpers/wait-for.ts';
+
+const git = (root: string, ...args: string[]) => execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim();
+const OPTS = { sourceId: 'default', noPull: true, noEmbed: true, noExtract: true };
+const setup = ({ root }: { root: string }) => {
+ git(root, 'init', '-q');
+ writeFileSync(join(root, 'pending.md'), 'An observation waiting for publication.\n');
+ git(root, 'add', '-A'); git(root, '-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-qm', 'pending');
+};
+const requestState = async (engine: BrainEngine) =>
+ (await engine.executeRaw<{ state: string }>("SELECT state FROM persistence_requests WHERE source_id='default' AND intent->>'kind'='managed_sync_import'")).map(row => row.state);
+const carried = async (engine: BrainEngine) => (await engine.executeRaw<{ carried: unknown }>(
+ "SELECT completed_keys->0->'obligations'->'pending_requests' AS carried FROM op_checkpoints WHERE op=$1", [MANAGED_SYNC_PASS_OP]))[0]?.carried ?? null;
+
+/** Leaves the source's one import open past a `writer_pending` stop: the worktree lock is held while the pass waits. */
+async function stopPending(engine: BrainEngine): Promise<void> {
+ await disposePersistenceConsumer(engine);
+ const lock = await acquireWorktree((await getWorktreeBinding(engine, 'default'))!);
+ expect(lock).not.toBeNull();
+ try {
+ expect(await performManagedSync(engine, OPTS)).toMatchObject({ status: 'partial', reason: 'writer_pending', added: 0 });
+ } finally { await disposePersistenceConsumer(engine); await lock!.release(); }
+ expect(await requestState(engine)).toEqual(['queued']);
+}
+
+/** At `point` in round 1 of the next pass: the consumer commits the open import before the pass goes on. */
+const commitAt = (engine: BrainEngine, point: FaultPoint) => installFaultHook(async (at, detail) => {
+ if (at !== point || detail.round !== 1) return;
+ installFaultHook(undefined);
+ startPersistenceConsumer(engine, { engine: engine.kind }).wake(true);
+ await waitFor(async () => (await requestState(engine))[0] === 'committed', { timeoutMs: 30_000, label: 'carried import committed' });
+});
+
+afterEach(() => installFaultHook(undefined));
+
+for (const backend of testBackends()) {
+ const databaseUrl = backend === 'postgres' ? process.env.DATABASE_URL : undefined;
+ describe(`#6712 PR 4b carried pass requests (${backend})`, () => {
+ const cases: Array<[string, FaultPoint | null]> = [
+ ['commits before the level read', 'sync:round_start'],
+ ['commits after the level read saw it in flight', 'sync:level_read'],
+ ['commits while the pass waits on it', null],
+ ];
+ for (const [label, point] of cases) {
+ test(`a prior pass's open import that ${label} is the resumed pass's import, counted once`, () => managedBrain(async ({ engine }) => {
+ await stopPending(engine);
+ if (point) commitAt(engine, point);
+ const resumed = await performManagedSync(engine, OPTS);
+ expect(resumed).toMatchObject({ status: 'first_sync', added: 1, modified: 0, filesImported: 1 });
+ expect(await requestState(engine)).toEqual(['committed']);
+ expect(await carried(engine)).toBeNull();
+ expect(await performManagedSync(engine, OPTS)).toMatchObject({ status: 'up_to_date', added: 0, modified: 0, filesImported: 0 });
+ }, { databaseUrl, setup }), 90_000);
+ }
+ });
+}