Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(sync): commit→embedded samples only a receipt that is still the page's current revision

garrytan13f53b8a92b5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9a0fe5b4fd..44ab5fa0e6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,7 +32,7 @@ To turn it on, run `gbrain config set sync.on_commit true` on the brain host. Th
### Itemized changes
- New `src/core/serve-head-watcher.ts`, started next to the movement watch in `gbrain serve` and `gbrain serve --http`. With `sync.on_commit` on it polls `git rev-parse HEAD` in the checkout of each managed source this host owns every 3 s (`GBRAIN_SERVE_HEAD_POLL_MS`, 1 to 30 s), with an `fs.watch` on the git directory that only brings the next poll forward, debounces 3 s (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and starts one managed sync through the existing `startDelegatedSync` as this host's CLI writer. It never starts beside a running delegated sync or a held drain lease, skips a commit the source has already synced, resumes a resumable stop up to three times, never writes into the checkout or `.git`, and logs each distinct error once. With the setting off it makes no git call.
-- New `src/core/persistence/sync-freshness.ts`: commit→searchable and commit→embedded p50/p95 per managed source from existing columns (the commit's committer time from git, `persistence_requests.completed_at` of committed `managed_sync_import` receipts, `content_chunks.embedded_at`). First syncs and working-tree entries are not counted; a run that spans several commits is dated by its newest. No schema change.
+- New `src/core/persistence/sync-freshness.ts`: commit→searchable and commit→embedded p50/p95 per managed source from existing columns (the commit's committer time from git, `persistence_requests.completed_at` of committed `managed_sync_import` receipts, `content_chunks.embedded_at`). Commit→embedded counts only a receipt that is still the page's current revision, and only an embedding at or after its write, so a later revision never rewrites an earlier sample. First syncs and working-tree entries are not counted; a run that spans several commits is dated by its newest. No schema change.
- New config keys `sync.on_commit` and `sync.freshness_target_seconds` (tunables in `src/core/sync-config-keys.ts`).
- New doctor check `managed_sync_latency` (`src/commands/doctor/checks/managed-sync-latency.ts`); the doctor goldens are regenerated for it.
- Tests: `test/serve-head-watcher.test.ts` (debounce, single flight, follow-up, resume cap, error handling, stop), `test/serve-head-watcher-managed.serial.test.ts` (a real managed source on PGLite and Postgres: a commit becomes searchable with no manual sync), `test/serve-http-head-watcher.serial.test.ts` (the watcher starts with `gbrain serve --http` and its poll interval is cleared on shutdown), `test/sync-freshness-6858.test.ts` (percentiles, exclusions, doctor thresholds, the additive `sync status --json` block). The two database tests are listed in `test/postgres-unit-arms.txt`.
diff --git a/docs/architecture/key-files/managed-sync-bookkeeping.md b/docs/architecture/key-files/managed-sync-bookkeeping.md
index 877aabfd38..883f2045cb 100644
--- a/docs/architecture/key-files/managed-sync-bookkeeping.md
+++ b/docs/architecture/key-files/managed-sync-bookkeeping.md
@@ -40,4 +40,4 @@ run, and the supersession of a checkpoint whose cursor another run replaced. The
- `src/core/since.ts` — #6712 PR 2: `parseSince(input, flag, now)`, the one `--since` parser (`gbrain agent logs --since`, `gbrain repair file-drift --since`). An age (`90s`, `30m`, `12h`, `7d`) becomes one concrete UTC instant at parse time; an ISO-8601 date or timestamp is normalized; anything else throws `invalid_params` naming the flag. Callers print and hash the instant, never the age. Tests: `test/sync-exits-l4-6712.test.ts`, `test/agent-cli.test.ts`.
- `src/core/persistence/sync-ghosts.ts` — #6712 PR 2: `countSyncGhosts(engine, sourceId)`, the post-sync ghost count. It reuses `scanGhostSource` from `repair/ghost-pages.ts` (no second classifier) with a candidate bound of `SYNC_GHOST_CHECK_LIMIT` (50) stats, leaves out paths sync holds (a held file is the hold's to explain), and returns the count, samples and the `gbrain repair ghost-pages --source <id>` preview as its fix. Sync never deletes or tombstones a ghost; `commands/sync/perform.ts` prints one line and sets `SyncResult.ghostPages`. Test: `test/sync-exits-l4-6712.test.ts`.
- `src/core/persistence/soak-counters.ts` — #6712 PR 2: the soak counters doctor `sync_soak_counters` reports (one `op_checkpoints` row per UTC day under op `sync-soak-counters`). Interventions: `sync_non_plain` (`nonPlainSyncFlags`, from `sync/run.ts`), `repair_apply` (`repair.ts`), `unblock_apply` (`sync/operator.ts`), `retry_held` (`sources-retry-held.ts`) and `needs_human` (`sweepNeedsHumanHolds`, run after each managed sync: stamps `needs_human_at` on a hold the fault table now calls `needs_human` and counts it once; the stamp survives same-code re-holds). Content decisions: `file_drift_apply` and `file_drift_hold`. `readSoakCounters` sums the last seven days. Counting never fails the command that counts. Test: `test/sync-exits-l4-6712.test.ts`.
-- `src/core/serve-head-watcher.ts` + `src/core/persistence/sync-freshness.ts` + `src/commands/doctor/checks/managed-sync-latency.ts` — #6858 ask 6: on-commit sync and its latency metric. `startServeHeadWatcher` (two call sites: `installResidentTickers` in `src/commands/serve.ts`, stopped before `shutdownDelegatedSync`, and `runServeHttp` in `src/commands/serve-http.ts`, beside `startMovementWatch` and stopped on the same shutdown path) re-reads `sync.on_commit` every 30 s; while on it polls `git rev-parse HEAD` in each managed source checkout this host owns (`GBRAIN_SERVE_HEAD_POLL_MS`, default 3 s; an `fs.watch` on the git dir only nudges the poll), debounces 3 s (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and starts one managed sync through the unchanged `startDelegatedSync` with this host's `cli` registration. It never starts beside a running delegated sync or a held drain lease (the move stays pending and fires once after), skips a HEAD `sources.last_commit` already has, resumes a resumable stop up to `MAX_RESUMES`, and logs each distinct error once. `readSyncFreshness` samples committed `managed_sync_import` receipts of the last 24 h (not first syncs or working-tree entries): commit time is the git committer time of `intent.target`, searchable is `completed_at`, embedded is the page's newest `content_chunks.embedded_at` once every chunk has one; p50/p95 in one aggregate over the `persistence_requests_sync_watermark` predicate. `gbrain sync status` (the `freshness` block) and `gbrain status` print it; doctor `managed_sync_latency` grades p95 against `sync.freshness_target_seconds` (default 300; fail over max(1 h, target)) only with `sync.on_commit` on or a target set. Tests: `test/serve-head-watcher.test.ts`, `test/serve-head-watcher-managed.serial.test.ts`, `test/serve-http-head-watcher.serial.test.ts`, `test/sync-freshness-6858.test.ts`.
+- `src/core/serve-head-watcher.ts` + `src/core/persistence/sync-freshness.ts` + `src/commands/doctor/checks/managed-sync-latency.ts` — #6858 ask 6: on-commit sync and its latency metric. `startServeHeadWatcher` (two call sites: `installResidentTickers` in `src/commands/serve.ts`, stopped before `shutdownDelegatedSync`, and `runServeHttp` in `src/commands/serve-http.ts`, beside `startMovementWatch` and stopped on the same shutdown path) re-reads `sync.on_commit` every 30 s; while on it polls `git rev-parse HEAD` in each managed source checkout this host owns (`GBRAIN_SERVE_HEAD_POLL_MS`, default 3 s; an `fs.watch` on the git dir only nudges the poll), debounces 3 s (`GBRAIN_SERVE_HEAD_DEBOUNCE_MS`) and starts one managed sync through the unchanged `startDelegatedSync` with this host's `cli` registration. It never starts beside a running delegated sync or a held drain lease (the move stays pending and fires once after), skips a HEAD `sources.last_commit` already has, resumes a resumable stop up to `MAX_RESUMES`, and logs each distinct error once. `readSyncFreshness` samples committed `managed_sync_import` receipts of the last 24 h (not first syncs or working-tree entries): commit time is the git committer time of `intent.target`, searchable is `completed_at`, embedded is the page's newest `content_chunks.embedded_at` once every chunk has one, sampled only from a receipt no later committed write to the same page supersedes and only at or after its `completed_at`; p50/p95 in one aggregate over the `persistence_requests_sync_watermark` predicate. `gbrain sync status` (the `freshness` block) and `gbrain status` print it; doctor `managed_sync_latency` grades p95 against `sync.freshness_target_seconds` (default 300; fail over max(1 h, target)) only with `sync.on_commit` on or a target set. Tests: `test/serve-head-watcher.test.ts`, `test/serve-head-watcher-managed.serial.test.ts`, `test/serve-http-head-watcher.serial.test.ts`, `test/sync-freshness-6858.test.ts`.
diff --git a/docs/guides/live-sync.md b/docs/guides/live-sync.md
index 5100ff1314..28cc44ed6d 100644
--- a/docs/guides/live-sync.md
+++ b/docs/guides/live-sync.md
@@ -240,7 +240,8 @@ Each managed source's freshness over the last 24 hours shows in
`gbrain sync status --source <id>` (the `freshness` block in `--json`) and
in `gbrain status`: p50 and p95 of commit→searchable (from the commit's
committer time to the page write's `completed_at`) and commit→embedded (to
-the page's last chunk embedding). A first sync and working-tree entries are not
+the page's last chunk embedding, counted only while that write is still the
+page's current revision and only for an embedding after the write). A first sync and working-tree entries are not
counted, and a run that spans several commits is dated by its newest. Doctor
`managed_sync_latency` warns when p95 commit→searchable is over
`sync.freshness_target_seconds` (default 300) and fails over one hour; it
diff --git a/llms-full.txt b/llms-full.txt
index e66a1c039b..8f16f01433 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -6844,7 +6844,8 @@ Each managed source's freshness over the last 24 hours shows in
`gbrain sync status --source <id>` (the `freshness` block in `--json`) and
in `gbrain status`: p50 and p95 of commit→searchable (from the commit's
committer time to the page write's `completed_at`) and commit→embedded (to
-the page's last chunk embedding). A first sync and working-tree entries are not
+the page's last chunk embedding, counted only while that write is still the
+page's current revision and only for an embedding after the write). A first sync and working-tree entries are not
counted, and a run that spans several commits is dated by its newest. Doctor
`managed_sync_latency` warns when p95 commit→searchable is over
`sync.freshness_target_seconds` (default 300) and fails over one hour; it
diff --git a/src/core/persistence/sync-freshness.ts b/src/core/persistence/sync-freshness.ts
index 458bd71559..8e01024412 100644
--- a/src/core/persistence/sync-freshness.ts
+++ b/src/core/persistence/sync-freshness.ts
@@ -8,8 +8,11 @@
* are not samples: they import history or uncommitted files, not a commit that just landed.
* - searchable: the receipt's `completed_at` (the page write committed; search reads it from then on).
* - embedded: the newest `content_chunks.embedded_at` of the page's visible chunks, once every one has one (a page with a
- * chunk still waiting counts as `pending`; a page with no chunks is not an embedding sample). A chunk embedded
- * before the write committed counts as embedded at the write.
+ * chunk still waiting counts as `pending`; a page with no chunks is not an embedding sample). Only a receipt whose
+ * write is still the page's current revision is an embedding sample: the chunks are the page's current ones, so a
+ * receipt superseded by a later committed write to the same page (same source and slug, higher sequence) would
+ * read the later revision's embed time; it still counts for commit→searchable. An embed time before the receipt's
+ * completion (chunks the write did not re-embed) is not a sample either.
* Latencies are clamped at 0 (a committer clock ahead of the database clock). The read uses the partial index
* `persistence_requests_sync_watermark` (its predicate is repeated verbatim) and stops after one probe when the window
* is empty. Nothing is written. Readers: `gbrain sync status` (the `freshness` block), `gbrain status`, and doctor
@@ -91,14 +94,15 @@ export async function readSyncFreshness(engine: BrainEngine, opts: { sourceIds?:
const commits = Object.keys(times).length;
if (!commits) { out.push({ ...empty, unresolved_commits: targets.length }); continue; }
const [row] = await engine.executeRaw<AggregateRow>(`WITH c AS (SELECT key AS target, to_timestamp(value::double precision) AS committed_at FROM jsonb_each_text($4::text::jsonb)),
- s AS (SELECT r.completed_at, c.committed_at, COALESCE(r.page_id, (SELECT p.id FROM pages p WHERE p.source_id=r.source_id AND p.slug=r.slug LIMIT 1)) AS page_id
+ s AS (SELECT r.completed_at, c.committed_at, COALESCE(r.page_id, (SELECT p.id FROM pages p WHERE p.source_id=r.source_id AND p.slug=r.slug LIMIT 1)) AS page_id,
+ EXISTS (SELECT 1 FROM persistence_requests later WHERE later.source_id=r.source_id AND later.slug=r.slug AND later.sequence>r.sequence AND later.state='committed') AS superseded
FROM persistence_requests r JOIN c ON c.target=r.intent->>'target' WHERE ${SAMPLE_WHERE}),
- e AS (SELECT s.completed_at, s.committed_at, ch.n, ch.missing, ch.last_at FROM s
+ e AS (SELECT s.completed_at, s.committed_at, s.superseded, ch.n, ch.missing, ch.last_at FROM s
LEFT JOIN LATERAL (SELECT count(*) AS n, count(*) FILTER (WHERE cc.embedded_at IS NULL) AS missing, max(cc.embedded_at) AS last_at FROM content_chunks cc JOIN pages p ON p.id=cc.page_id
WHERE cc.page_id=s.page_id AND ${chunkVisibleFilter('p', 'cc')}) ch ON true),
l AS (SELECT GREATEST(0, extract(epoch FROM completed_at - committed_at)) AS searchable,
- CASE WHEN n > 0 AND missing = 0 THEN GREATEST(0, extract(epoch FROM GREATEST(last_at, completed_at) - committed_at)) END AS embedded,
- (n > 0 AND missing > 0) AS pending FROM e)
+ CASE WHEN NOT superseded AND n > 0 AND missing = 0 AND last_at >= completed_at THEN GREATEST(0, extract(epoch FROM last_at - committed_at)) END AS embedded,
+ (NOT superseded AND n > 0 AND missing > 0) AS pending FROM e)
SELECT count(*) AS samples, percentile_cont(0.5) WITHIN GROUP (ORDER BY searchable) AS s50, percentile_cont(0.95) WITHIN GROUP (ORDER BY searchable) AS s95,
count(embedded) AS embedded, percentile_cont(0.5) WITHIN GROUP (ORDER BY embedded) AS e50, percentile_cont(0.95) WITHIN GROUP (ORDER BY embedded) AS e95,
count(*) FILTER (WHERE pending) AS pending FROM l`, [b.worktree_id, b.source_incarnation, FRESHNESS_WINDOW_HOURS, JSON.stringify(times)]);
diff --git a/test/sync-freshness-6858.test.ts b/test/sync-freshness-6858.test.ts
index 51e417615e..3face6bf67 100644
--- a/test/sync-freshness-6858.test.ts
+++ b/test/sync-freshness-6858.test.ts
@@ -128,6 +128,41 @@ describe('sync freshness (#6858 ask 6)', () => {
}
}), 120_000);
+ test('a later revision of the page does not rewrite an earlier receipt\'s commit→embedded; an embed before the write is no sample', () => withEnv({ GBRAIN_HOME: home }, async () => {
+ for (const { name, engine } of engines) {
+ await reset(engine);
+ const f = await managedSource(engine, 7200);
+ const later = 'b'.repeat(40);
+ const commitTimes = async () => new Map([[f.sha, f.committedAt], [later, f.committedAt + 3600]]);
+ const slug = 'notes/alice-example';
+ const at = (s: number) => new Date((f.committedAt + s) * 1000).toISOString();
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ const [page] = await engine.executeRaw<{ id: number }>("INSERT INTO pages(source_id,slug,type,title) VALUES($1,$2,'note',$2) RETURNING id", [f.id, slug]);
+ await engine.executeRaw('UPDATE pages SET text_projection_revision=knowledge_revision WHERE id=$1', [page!.id]);
+ await engine.executeRaw("INSERT INTO content_chunks(page_id,chunk_index,chunk_text,embedded_at) VALUES($1,0,'first revision',$2::timestamptz)", [page!.id, at(12)]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ const write = async (target: string, completedAfter: number) => engine.executeRaw(`INSERT INTO persistence_requests(principal_kind,principal_id,request_id,operation,source_id,source_incarnation,slug,page_id,worktree_id,digest,authority,intent,intent_bytes,terminal_reservation,state,completed_at)
+ VALUES('local_cli','cli:example',$1::uuid,'submit_job',$2,$3::uuid,$4,$5,$6::uuid,'d','{}'::jsonb,$7::text::jsonb,1,16384,'committed',$8::timestamptz)`,
+ [randomUUID(), f.id, f.incarnation, slug, page!.id, f.worktreeId, JSON.stringify({ kind: 'managed_sync_import', path: `${slug}.md`, target, from: FROM, runId: randomUUID(), index: 0, total: 1 }), at(completedAfter)]);
+ await write(f.sha, 10);
+ const [first] = await readSyncFreshness(engine, { sourceIds: [f.id], commitTimes });
+ expect(first!.commit_to_embedded, name).toEqual({ samples: 1, p50_seconds: 12, p95_seconds: 12, pending: 0 });
+ // The second revision: committed 3600 s later, written 10 s after it and embedded 12 s after it.
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=false WHERE singleton=1');
+ await engine.executeRaw("UPDATE content_chunks SET chunk_text='second revision', embedded_at=$1::timestamptz WHERE page_id=$2", [at(3612), page!.id]);
+ await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
+ await write(later, 3610);
+ const [both] = await readSyncFreshness(engine, { sourceIds: [f.id], commitTimes });
+ expect(both, name).toMatchObject({ commits: 2, commit_to_searchable: { samples: 2, p50_seconds: 10, p95_seconds: 10 },
+ commit_to_embedded: { samples: 1, p50_seconds: 12, p95_seconds: 12, pending: 0 } });
+ // A third write whose chunks kept the earlier embed time (nothing re-embedded): searchable, but no embedding sample.
+ await write(later, 3700);
+ const [kept] = await readSyncFreshness(engine, { sourceIds: [f.id], commitTimes });
+ expect(kept!.commit_to_searchable.samples, name).toBe(3);
+ expect(kept!.commit_to_embedded, name).toEqual({ samples: 0, p50_seconds: null, p95_seconds: null, pending: 0 });
+ }
+ }), 120_000);
+
test('a commit this checkout cannot date is counted unresolved, not sampled', () => withEnv({ GBRAIN_HOME: home }, async () => {
for (const { engine } of engines) {
await reset(engine);