Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): refresh last_sync_at on managed up-to-date runs (#5443)

time-attacke20e0e5ee67e
diff --git a/docs/architecture/canonical-writers.tsv b/docs/architecture/canonical-writers.tsv
index 1ab58624b1..fd23730b79 100644
--- a/docs/architecture/canonical-writers.tsv
+++ b/docs/architecture/canonical-writers.tsv
@@ -127,6 +127,7 @@ src/commands/schema.ts 0 filesystem_guard Schema manifest scaffolding and forks
src/core/ingestion/sources/inbox-folder.ts 0 filesystem_guard Inbox archive moves refuse managed canonical input paths before emitting the event or moving source bytes.
src/core/persistence/links-preparation.ts 2 coordinator Automatic graph projections publish inside canonical page transactions; delayed reconciliation locks all affected page keys and compares the originating revision.
src/core/persistence/sync-prepare.ts 8 coordinator Managed imports and deletes validate the recorded raw file hash plus enumerated page identity/revision; a managed rename moves the page with updateSlug and re-infers an implicit type inside the same journal publication after the renamed page's identity and revision are rechecked; the source-exclusive final checkpoint requires every selected receipt to be committed. Its importFromContent calls carry prepare and run inside the coordinator publication. The checkpoint also stamps sources.chunker_version after a full walk (#5566), inside the same source-exclusive publication; the column is outside managed_writer_guard's protected checkpoint tuple.
+src/core/persistence/sync-run.ts 1 coordinator The managed up-to-date heartbeat stamps only sources.last_sync_at inside withCoordinatedWrite, scoped to the checked source id and incarnation; no checkpoint, commit or content-freshness column changes.
src/commands/enrich.ts 0 coordinator A managed brain preflights maintenance authority before any model spend and publishes each enriched page through publishMaintenancePage; unmanaged enrichment writes through the put_page operation.
src/core/persistence/source-lifecycle.ts 6 coordinator Native affected roots precede topology, source, principal and receipt guards; every shared-root generation and old queued intent changes together.
src/core/persistence/topology-recovery.ts 2 coordinator Verified directory-swap recovery checks source incarnation, current logical manifest and physical identity before topology commitment; permanent receipt IDs survive deletion.
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 4f4ce84fad..17cce193f8 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -38,6 +38,8 @@ import { isContentRefusal } from '../import-screen.ts';
import { SYNC_READ_BOUND, type TreeBlob } from './sync-blobs.ts';
import { dryRunScreen, isSyncReadBound, loadSyncScreenRun, managedImageHold, pinnedBlob, screenFrozenImport, type HeldEntry, type SyncScreenRun } from './sync-screen.ts';
import { faultPoint } from './fault-points.ts';
+import { withCoordinatedWrite } from './context.ts';
+import { principalAttribution } from './attribution.ts';
import { addRecovered, buildHoldReport, clearGitHold, clearGitHoldRetryPaths, readSyncHoldPolicy, recordSyncConversion, recoveredReport, writeGitHold } from './sync-holds.ts';
export interface ManagedSyncWriteDiagnostic {
@@ -735,6 +737,11 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
const fresh: Cursor = { ...discovery, authority, processingOptions, syncOptions, runId: discoveryRun, index: 0, counts: { added: 0, modified: 0, deleted: 0, chunks: 0 }, ...(company ? { companyReceiptId: company.receiptId } : {}) };
if (opts.dryRun) return dryRun(fresh);
if (!fresh.entries.length && fresh.from === fresh.target) {
+ // A complete check that found nothing is still a sync: stamp the freshness heartbeat for this incarnation only.
+ await engine.transaction(tx => withCoordinatedWrite(tx, [context.sourceId], () => {
+ assertActive();
+ return tx.executeRaw('UPDATE sources SET last_sync_at=now() WHERE id=$1 AND incarnation=$2::uuid', [context.sourceId, context.incarnation]);
+ }, principalAttribution(authority.writer.principal)));
await clearManagedSyncFailureAfterSuccess(engine, key);
assertActive();
return result(fresh, 'up_to_date');
diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.ts
index 25f5392fac..c3357e15d5 100644
--- a/test/persistence-managed-sync.test.ts
+++ b/test/persistence-managed-sync.test.ts
@@ -134,6 +134,78 @@ test('after a trailing-commit skip, the commit that carries the page bytes impor
}
}),120_000);
+const OLD_SYNC_AT = '2000-01-01T00:00:00Z';
+async function backdateLastSync(engine: BrainEngine, id: string): Promise<void> {
+ await engine.transaction(tx => withCoordinatedWrite(tx, [id], () => tx.executeRaw('UPDATE sources SET last_sync_at=$2::timestamptz WHERE id=$1', [id, OLD_SYNC_AT]), TEST_WRITE_ATTRIBUTION));
+}
+async function lastSyncMs(engine: BrainEngine, id: string): Promise<number> {
+ const [row] = await engine.executeRaw<{ last_sync_at: Date | string }>('SELECT last_sync_at FROM sources WHERE id=$1', [id]);
+ return Date.parse(String(row.last_sync_at));
+}
+
+test('managed sync refreshes quiet-source freshness only after a complete up-to-date check', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const f = await fixture(engine, { 'notes/example.md': 'A stable observation for heartbeat coverage.\n' });
+ await performManagedSync(engine, { sourceId: f.id, noPull: true });
+ await backdateLastSync(engine, f.id);
+ const columns = 'SELECT last_commit,newest_content_at,incarnation FROM sources WHERE id=$1';
+ const [before] = await engine.executeRaw(columns, [f.id]);
+ const checkpoints = await engine.executeRaw('SELECT count(*)::int AS n FROM persistence_requests');
+
+ expect((await performManagedSync(engine, { sourceId: f.id, noPull: true, dryRun: true })).status).toBe('dry_run');
+ expect(await lastSyncMs(engine, f.id)).toBe(Date.parse(OLD_SYNC_AT));
+
+ expect((await performManagedSync(engine, { sourceId: f.id, noPull: true })).status).toBe('up_to_date');
+ expect(await lastSyncMs(engine, f.id)).toBeGreaterThan(Date.parse(OLD_SYNC_AT));
+ expect(await engine.executeRaw(columns, [f.id])).toEqual([before]);
+ expect(await engine.executeRaw('SELECT count(*)::int AS n FROM persistence_requests')).toEqual(checkpoints);
+
+ writeFileSync(join(f.root, 'notes/example.md'), 'A changed observation requiring a partial sync.\n');
+ commit(f.root, 'changed content');
+ await backdateLastSync(engine, f.id);
+ const abort = new AbortController();
+ const partial = await performManagedSync(engine, { sourceId: f.id, noPull: true, signal: abort.signal,
+ onProgress: progress => { if (progress.bankedFiles === 1) abort.abort(); } });
+ expect(partial.status).toBe('partial');
+ expect(await lastSyncMs(engine, f.id)).toBe(Date.parse(OLD_SYNC_AT));
+ }
+}),120_000);
+
+test('a stale up-to-date run does not stamp a source re-added under a new incarnation', async () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const engine of engines) {
+ const f = await fixture(engine, { 'notes/example.md': 'A stable observation for incarnation coverage.\n' });
+ await performManagedSync(engine, { sourceId: f.id, noPull: true });
+ await backdateLastSync(engine, f.id);
+ const reAdded = randomUUID();
+ const transaction = engine.transaction;
+ let rotated = false;
+ engine.transaction = async function <T>(this: BrainEngine, run: (tx: BrainEngine) => Promise<T>): Promise<T> {
+ return transaction.call(this, async tx => {
+ const executeRaw = tx.executeRaw;
+ tx.executeRaw = async function <R = Record<string, unknown>>(this: BrainEngine, sql: string, params?: unknown[], opts?: { signal?: AbortSignal }): Promise<R[]> {
+ if (!rotated && /^UPDATE sources SET last_sync_at\b/.test(sql)) {
+ rotated = true;
+ // The source was removed and re-added after this run's discovery: same id, new incarnation.
+ // The writer guard refuses an in-place incarnation change, so the fixture bypasses triggers for this one statement.
+ await executeRaw.call(this, 'SET LOCAL session_replication_role = replica');
+ await executeRaw.call(this, 'UPDATE sources SET incarnation=$2::uuid WHERE id=$1', [f.id, reAdded]);
+ await executeRaw.call(this, 'SET LOCAL session_replication_role = origin');
+ }
+ return executeRaw.call(this, sql, params, opts) as Promise<R[]>;
+ };
+ return run(tx);
+ }) as Promise<T>;
+ } as BrainEngine['transaction'];
+ try {
+ expect((await performManagedSync(engine, { sourceId: f.id, noPull: true })).status).toBe('up_to_date');
+ } finally { engine.transaction = transaction; }
+ expect(rotated).toBe(true);
+ const [row] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation FROM sources WHERE id=$1', [f.id]);
+ expect(row.incarnation).toBe(reAdded);
+ expect(await lastSyncMs(engine, f.id)).toBe(Date.parse(OLD_SYNC_AT));
+ }
+}),120_000);
+
test('interrupted cursor resumes its pinned target before a newer HEAD and never advances early', async () => withEnv({ GBRAIN_HOME: home }, async () => {
for (const engine of engines) {
const f = await fixture(engine, {'a.md':'First stable observation about engineering.\n','b.md':'Original second observation about engineering.\n'});