Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

#6712 PR 4b lane F: doctor managed_sync_blocked lists a pass stopped in discovery or on one file (GBRA-133 S-61)

garrytan3119ec5fc6fd
diff --git a/docs/guides/troubleshooting.md b/docs/guides/troubleshooting.md
index 18e3b06066..e42828477a 100644
--- a/docs/guides/troubleshooting.md
+++ b/docs/guides/troubleshooting.md
@@ -150,7 +150,7 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p
<a id="session-timeouts-not-applied"></a>**Doctor warns `persistence_session_timeouts` with `session_timeouts_not_applied`?** gbrain sets `statement_timeout` (`GBRAIN_STATEMENT_TIMEOUT`, default 5min) and `idle_in_transaction_session_timeout` as connection startup parameters, and a transaction-mode pooler (PgBouncer with `ignore_startup_parameters`, Supavisor) drops them: `SHOW statement_timeout` through the configured URL reads `0`, so a statement outside a transaction has no server-side bound and a relation lock held in another session (a migration's `ALTER TABLE pages` queued behind a long transaction, for example) holds it for as long as the lock lasts. Managed write *preparation* reads are not affected since v0.60.108: they run under a transaction-local `statement_timeout` of the write's remaining preparation budget, so a lock-blocked read ends at the budget and the member is released `preparation_deadline` with no statement left on the server (#6278). For every other autocommit statement, set the default on the role instead of the connection: `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` (read-only to check: `gbrain doctor --only persistence_session_timeouts --json`). Setting `GBRAIN_STATEMENT_TIMEOUT` has no effect through such a pooler.
-<a id="managed-sync-blocked"></a>**A managed sync run is blocked (doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health reports `sync_blocked`)?** The source's unfinished run stopped on a page request that did not commit and recorded the stop, so it resumes nothing by itself while the other sources keep syncing (#6858: one source stopped for 21 hours while every freshness job reported `completed`). Such a job now ends `dead`: its error names the stop and the run's `next` command, and `gbrain jobs get <id> --json` carries `outcome`, `drain` and `next` in its progress. Doctor warns as soon as a run is blocked and fails once it has been blocked for more than an hour; get_brain_health turns to `attention` past the same hour, with a count band and no source names. Run `gbrain sync status --source <id> --json` (read-only): it names the page, its fault class and its exit. Clear the cause it names and run the step it prints; the next freshness job resumes the run once the cause is gone. A page publication that `gbrain repair stuck-recovery --keep disk` abandoned is not a blocker: the next plain sync retries that page after the rest of its run, imports it when the kept file is committed, and holds it `worktree_dirty` otherwise.
+<a id="managed-sync-blocked"></a>**A managed sync run is blocked (doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health reports `sync_blocked`)?** The source's unfinished run stopped on a page request that did not commit and recorded the stop, so it resumes nothing by itself while the other sources keep syncing (#6858: one source stopped for 21 hours while every freshness job reported `completed`). Such a job now ends `dead`: its error names the stop and the run's `next` command, and `gbrain jobs get <id> --json` carries `outcome`, `drain` and `next` in its progress. Doctor warns as soon as a run is blocked and fails once it has been blocked for more than an hour; get_brain_health turns to `attention` past the same hour, with a count band and no source names. A sync pass that stopped before it finished (in discovery, path `<discovery>`, or on one file) counts as blocked too, until a later sync of the source succeeds. Run `gbrain sync status --source <id> --json` (read-only): it names the page, its fault class and its exit. Clear the cause it names and run the step it prints; the next freshness job resumes the run once the cause is gone. A page publication that `gbrain repair stuck-recovery --keep disk` abandoned is not a blocker: the next plain sync retries that page after the rest of its run, imports it when the kept file is committed, and holds it `worktree_dirty` otherwise.
<a id="managed-sync-not-moving"></a>**The catch-up is parked (`sources status --json` says `data_moving: false`, doctor warns `managed_sync_not_moving`, `gbrain sources writer movement` exited 1), or the drain stopped `drain_stalled` with `cause: owner_wedged_here`?** Liveness is not movement: `/health` can be ok, the pid alive and `sync_running: true` while no page has committed for weeks. A managed source is *not moving* when an unfinished `managed-sync` cursor has had neither a committed `managed_sync_*` receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` (600 s) while a drain or a full consumer is live on the owner host; with nothing live it is `movement_state: parked` (a cursor left between cron runs; informational, not scored). A parked cursor whose write queue still holds admitted requests while no consumer runs and nothing has moved for longer than that ceiling is stranded: nothing will ever drain it, so doctor `managed_sync_not_moving` fails (#6552, #6712 PR 2) and its fix is the resume sync with the cursor's stored options (`gbrain sync --source <id> …`), which consumes the queue itself; `details.stranded` counts such sources. When the sync backlog itself cannot be read, every surface says `movement_state: unknown` (`unknown.reason: backlog_read_failed`) instead of `nothing_pending`: doctor warns with `details.health: unknown`, `sources status` prints a `movement UNKNOWN` line, and `gbrain sources writer movement` exits 1 with code `movement_unknown` (`--warn-only` exits 0); rerun the movement command, and run `gbrain doctor --json` if the read keeps failing. Every surface routes to the same two read-only calls, so the agent reaches the owner, the step and the next action without SQL:
diff --git a/llms-full.txt b/llms-full.txt
index a1251d9b86..1d1d99ac86 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -10513,7 +10513,7 @@ Turning the `preparation_deadlines` switch off (`gbrain config set persistence.p
<a id="session-timeouts-not-applied"></a>**Doctor warns `persistence_session_timeouts` with `session_timeouts_not_applied`?** gbrain sets `statement_timeout` (`GBRAIN_STATEMENT_TIMEOUT`, default 5min) and `idle_in_transaction_session_timeout` as connection startup parameters, and a transaction-mode pooler (PgBouncer with `ignore_startup_parameters`, Supavisor) drops them: `SHOW statement_timeout` through the configured URL reads `0`, so a statement outside a transaction has no server-side bound and a relation lock held in another session (a migration's `ALTER TABLE pages` queued behind a long transaction, for example) holds it for as long as the lock lasts. Managed write *preparation* reads are not affected since v0.60.108: they run under a transaction-local `statement_timeout` of the write's remaining preparation budget, so a lock-blocked read ends at the budget and the member is released `preparation_deadline` with no statement left on the server (#6278). For every other autocommit statement, set the default on the role instead of the connection: `ALTER ROLE <gbrain role> SET statement_timeout = '5min'` (read-only to check: `gbrain doctor --only persistence_session_timeouts --json`). Setting `GBRAIN_STATEMENT_TIMEOUT` has no effect through such a pooler.
-<a id="managed-sync-blocked"></a>**A managed sync run is blocked (doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health reports `sync_blocked`)?** The source's unfinished run stopped on a page request that did not commit and recorded the stop, so it resumes nothing by itself while the other sources keep syncing (#6858: one source stopped for 21 hours while every freshness job reported `completed`). Such a job now ends `dead`: its error names the stop and the run's `next` command, and `gbrain jobs get <id> --json` carries `outcome`, `drain` and `next` in its progress. Doctor warns as soon as a run is blocked and fails once it has been blocked for more than an hour; get_brain_health turns to `attention` past the same hour, with a count band and no source names. Run `gbrain sync status --source <id> --json` (read-only): it names the page, its fault class and its exit. Clear the cause it names and run the step it prints; the next freshness job resumes the run once the cause is gone. A page publication that `gbrain repair stuck-recovery --keep disk` abandoned is not a blocker: the next plain sync retries that page after the rest of its run, imports it when the kept file is committed, and holds it `worktree_dirty` otherwise.
+<a id="managed-sync-blocked"></a>**A managed sync run is blocked (doctor `managed_sync_blocked`, a freshness `sync` job ended `dead`, or get_brain_health reports `sync_blocked`)?** The source's unfinished run stopped on a page request that did not commit and recorded the stop, so it resumes nothing by itself while the other sources keep syncing (#6858: one source stopped for 21 hours while every freshness job reported `completed`). Such a job now ends `dead`: its error names the stop and the run's `next` command, and `gbrain jobs get <id> --json` carries `outcome`, `drain` and `next` in its progress. Doctor warns as soon as a run is blocked and fails once it has been blocked for more than an hour; get_brain_health turns to `attention` past the same hour, with a count band and no source names. A sync pass that stopped before it finished (in discovery, path `<discovery>`, or on one file) counts as blocked too, until a later sync of the source succeeds. Run `gbrain sync status --source <id> --json` (read-only): it names the page, its fault class and its exit. Clear the cause it names and run the step it prints; the next freshness job resumes the run once the cause is gone. A page publication that `gbrain repair stuck-recovery --keep disk` abandoned is not a blocker: the next plain sync retries that page after the rest of its run, imports it when the kept file is committed, and holds it `worktree_dirty` otherwise.
<a id="managed-sync-not-moving"></a>**The catch-up is parked (`sources status --json` says `data_moving: false`, doctor warns `managed_sync_not_moving`, `gbrain sources writer movement` exited 1), or the drain stopped `drain_stalled` with `cause: owner_wedged_here`?** Liveness is not movement: `/health` can be ok, the pid alive and `sync_running: true` while no page has committed for weeks. A managed source is *not moving* when an unfinished `managed-sync` cursor has had neither a committed `managed_sync_*` receipt nor a head step advance for longer than `persistence.preparation_ceiling_ms` (600 s) while a drain or a full consumer is live on the owner host; with nothing live it is `movement_state: parked` (a cursor left between cron runs; informational, not scored). A parked cursor whose write queue still holds admitted requests while no consumer runs and nothing has moved for longer than that ceiling is stranded: nothing will ever drain it, so doctor `managed_sync_not_moving` fails (#6552, #6712 PR 2) and its fix is the resume sync with the cursor's stored options (`gbrain sync --source <id> …`), which consumes the queue itself; `details.stranded` counts such sources. When the sync backlog itself cannot be read, every surface says `movement_state: unknown` (`unknown.reason: backlog_read_failed`) instead of `nothing_pending`: doctor warns with `details.health: unknown`, `sources status` prints a `movement UNKNOWN` line, and `gbrain sources writer movement` exits 1 with code `movement_unknown` (`--warn-only` exits 0); rerun the movement command, and run `gbrain doctor --json` if the read keeps failing. Every surface routes to the same two read-only calls, so the agent reaches the owner, the step and the next action without SQL:
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 57d9cb6284..85d5014d61 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -933,6 +933,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.300.0', text: 'When managed sync hits an unexpected error while preparing one file (before anything is admitted), it now holds that file `page_write_failed` with `meta.write_failure.origin` `freeze` and the error in the hold message, and the rest of the source syncs; before, the source stopped on that file on every run. The next syncs re-test the file on their own until it has been held 3 times, so a passing fault clears without help. A deliberate refusal still stops the run, and so does a run in which most files fail that way (5 or more, and at least as many as prepared cleanly), which looks systemic. In a bulk group (Postgres) the failure is reported on the file that failed, not on the group\'s first file.' },
{ since: '0.60.300.0', text: '`gbrain sync status --json` no longer tells an agent to rerun a managed sync forever when every run stops on the same file with the same unclassified `storage_error`: the first such stop is still `connection` with `next` = rerun, but once two runs in a row stop on the same path with the same code and message, `last_error` is `needs_human` (class `page`, `safe_actions` `none`, new field `repeats`), the state is `blocked` / `needs_human`, and `human_reason` names the file. A message that changes between runs stays a rerun.' },
{ since: '0.60.300.0', text: 'A file whose exact bytes an earlier gbrain imported and validated, and which this release refuses (a parser regression), no longer stops the sync by default: it is held `parser_regression` alone (a gbrain bug to report; it needs a person) and the rest of the source syncs. `GBRAIN_SYNC_PARSER_REGRESSION=stop` for the process that syncs restores the old stop (`sync_parser_regression`, the checkpoint does not advance). A refusal this release makes on purpose, such as the YAML alias bound (`frontmatter_alias_limit`), is held as before under either setting.' },
+ { since: '0.60.300.0', text: 'Doctor `managed_sync_blocked` (and get_brain_health `sync_blocked`) now count a managed sync pass that stopped with a recorded failure before finishing, in discovery (path `<discovery>`) or on one file, until a later sync of the source succeeds; before, such a source indexed nothing while the check said no run was blocked.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/persistence/sync-blocked.ts b/src/core/persistence/sync-blocked.ts
index 4b3745d664..f65c5737f4 100644
--- a/src/core/persistence/sync-blocked.ts
+++ b/src/core/persistence/sync-blocked.ts
@@ -9,10 +9,16 @@
* stopping (`passHealth`: the newest ended `blocked`, a `not_converged` streak, a `settle_mismatch` streak), with the
* newest pass's stop reason as `code`, its pass id as `run_id` and `stuck_since` as `blocked_since`. A source listed by
* its pass is not listed again by a legacy cursor.
+ * GBRA-133 S-61: a pass that threw records its stop under a pass failure key (`passFailureKeys`) with no cursor, and its pass
+ * row stays `open`, so neither rule above saw it: a discovery-phase stop (path `<discovery>`) or an entry's stop read as
+ * nothing blocked while the source indexed nothing. Such a stop is listed while it is newer than the pass row (no pass has
+ * started since; a converged or idle pass clears it).
*/
import type { BrainEngine } from '../engine.ts';
import { readManagedSyncFailures } from './sync-failures.ts';
import { passFingerprint } from './sync-pass-row.ts';
+import { passFailureKeys } from './sync-cursor-key.ts';
+import type { ManagedSyncFailure } from './sync-failures.ts';
/** A run blocked longer than this fails doctor `managed_sync_blocked` and turns get_brain_health to `attention`. */
export const MANAGED_SYNC_BLOCKED_FAIL_MS = 60 * 60_000;
@@ -27,13 +33,23 @@ export async function readBlockedManagedSyncs(engine: BrainEngine, sourceIds?: s
const failures = await readManagedSyncFailures(engine, sourceIds);
// A pass blocked by a failed write names that write's code (its failure row is keyed by the pass fingerprint), as a cursor did.
const passFailure = (sourceId: string, incarnation: string) => failures.find(failure => failure.cursor_key === passFingerprint(sourceId, incarnation) && failure.code !== 'sync_incomplete');
- const passes: BlockedManagedSync[] = (await readPassReadings(engine, { sourceIds, head: false })).filter(reading => passStuck(reading.health))
+ const readings = await readPassReadings(engine, { sourceIds, head: false });
+ const passes: BlockedManagedSync[] = readings.filter(reading => passStuck(reading.health))
.map(reading => {
const failure = passStopCode(reading) === 'blocked_by_failures' ? passFailure(reading.source_id, reading.row.value.incarnation) : undefined;
return { source_id: reading.source_id, code: failure?.code ?? passStopCode(reading), run_id: reading.row.value.telemetry.pass_id, blocked_since: failure?.first_seen ?? passStuckSince(reading.row) };
});
const passSources = new Set(passes.map(blocked => blocked.source_id));
+ const passRowAt = new Map(readings.map(reading => [reading.source_id, Date.parse(reading.row.updated_at)]));
+ const passStops = (await engine.executeRaw<{ fingerprint: string; updated_at: string | Date; failure: ManagedSyncFailure }>(`
+ SELECT f.fingerprint, f.updated_at, f.completed_keys->0 AS failure FROM op_checkpoints f
+ JOIN sources s ON s.id=f.completed_keys->0->>'source_id' AND s.incarnation::text=f.completed_keys->0->>'source_incarnation'
+ WHERE f.op='managed-sync-failure' AND ($1::text[] IS NULL OR s.id=ANY($1::text[]))
+ AND NOT EXISTS(SELECT 1 FROM op_checkpoints c WHERE c.op='managed-sync' AND c.fingerprint=f.fingerprint)`, [sourceIds ?? null]))
+ .filter(({ fingerprint, updated_at, failure }) => !passSources.has(failure.source_id) && failure.code !== 'sync_incomplete'
+ && passFailureKeys(failure.source_id, failure.source_incarnation).includes(fingerprint) && new Date(updated_at).getTime() >= (passRowAt.get(failure.source_id) ?? 0))
+ .map(({ failure }) => ({ source_id: failure.source_id, code: failure.code, run_id: failure.run_id, blocked_since: failure.first_seen }));
return [...failures
.filter(failure => failure.code !== 'sync_incomplete' && cursors.has(failure.cursor_key) && !passSources.has(failure.source_id))
- .map(failure => ({ source_id: failure.source_id, code: failure.code, run_id: failure.run_id, blocked_since: failure.first_seen })), ...passes];
+ .map(failure => ({ source_id: failure.source_id, code: failure.code, run_id: failure.run_id, blocked_since: failure.first_seen })), ...passes, ...passStops];
}
diff --git a/src/core/persistence/sync-cursor-key.ts b/src/core/persistence/sync-cursor-key.ts
index 2013efe1b4..bf0dadaa83 100644
--- a/src/core/persistence/sync-cursor-key.ts
+++ b/src/core/persistence/sync-cursor-key.ts
@@ -33,6 +33,7 @@ import { clearManagedSyncFailureAfterSuccess } from './sync-failures.ts';
import { assertDrainLease } from './sync-lease.ts';
import { faultPoint } from './fault-points.ts';
import { SYNC_SLICE_OP } from './sync-slices.ts';
+import { passFingerprint } from './sync-pass-row.ts';
type CompanySync = ReturnType<typeof currentCompanyBrainSync>;
@@ -47,6 +48,9 @@ export function managedCursorKey(incarnation: string, company: CompanySync): str
return keyForTests?.(incarnation) ?? digest({ source: incarnation, ...companyPart(company) });
}
+/** #6712 PR 4b: where a pass records its stops (the pass row's key, and the incarnation's cursor key for discovery); a converged or idle pass clears both. */
+export const passFailureKeys = (sourceId: string, incarnation: string) => [passFingerprint(sourceId, incarnation), managedCursorKey(incarnation, undefined)];
+
export const SUPERSEDED_BY_ADOPTION_MESSAGE = 'Another unfinished sync run of this source was adopted; this queued page of a superseded run was not published, and the adopted run (or the next sync) imports it.';
export interface CursorResolution {
diff --git a/src/core/persistence/sync-pass-run.ts b/src/core/persistence/sync-pass-run.ts
index b9d69935b6..e56fd69168 100644
--- a/src/core/persistence/sync-pass-run.ts
+++ b/src/core/persistence/sync-pass-run.ts
@@ -46,7 +46,7 @@ import { loadActivePackForEngine } from '../schema-pack/engine-resolution.ts';
import { loadConfig } from '../config.ts';
import { startPersistenceConsumer } from './service.ts';
import { clearManagedSyncFailureAfterSuccess } from './sync-failures.ts';
-import { managedCursorKey, resolveManagedCursor, retireManagedCursor, retireOrphanSliceRecords } from './sync-cursor-key.ts';
+import { managedCursorKey, passFailureKeys, resolveManagedCursor, retireManagedCursor, retireOrphanSliceRecords } from './sync-cursor-key.ts';
import { withCoordinatedWrite } from './context.ts';
import { pipelined } from '../page-state/transactions.ts';
import { principalAttribution } from './attribution.ts';
@@ -914,7 +914,6 @@ async function databaseNow(tx: Pick<BrainEngine, 'executeRaw'>): Promise<string>
}
/** A converged or idle pass clears what earlier stops recorded: the pass row's failure key and the incarnation's cursor key. */
-const passFailureKeys = (sourceId: string, incarnation: string) => [passFingerprint(sourceId, incarnation), managedCursorKey(incarnation, undefined)];
async function clearPassFailures(engine: BrainEngine, sourceId: string, incarnation: string): Promise<void> {
await Promise.all(passFailureKeys(sourceId, incarnation).map(key => clearManagedSyncFailureAfterSuccess(engine, key)));
}
diff --git a/test/behavior-change-notice-6712-block.test.ts b/test/behavior-change-notice-6712-block.test.ts
index 26916a9128..70affc03da 100644
--- a/test/behavior-change-notice-6712-block.test.ts
+++ b/test/behavior-change-notice-6712-block.test.ts
@@ -12,7 +12,7 @@ import { join } from 'node:path';
import { BEHAVIOR_CHANGES, compareReleases } from '../src/core/behavior-change-notice.ts';
const MARKER = '// #6712 PR 4b (the level-triggered sync pass';
-const ROWS = 29;
+const ROWS = 30;
const NOTICE_CAP = 2_000;
/** The array literal's row lines in order, and where the block's rows start and how many there are. */
diff --git a/test/sync-entry-faults-6712.test.ts b/test/sync-entry-faults-6712.test.ts
index c4bf9e501a..7860fb57f8 100644
--- a/test/sync-entry-faults-6712.test.ts
+++ b/test/sync-entry-faults-6712.test.ts
@@ -18,6 +18,8 @@
* - S-60: a `storage_error` that two syncs in a row record on one file with the same message stayed `connection` / `retry`
* with `next` = rerun the same sync forever; it is now `page` class and `needs_human`, naming the file. A message that
* changes between runs stays a rerun, and the count survives a resumed cursor's repeated observation.
+ * - S-61: a pass that stopped in discovery (path `<discovery>`) or on one entry left no cursor and an `open` pass row, so
+ * doctor `managed_sync_blocked` (`readBlockedManagedSyncs`) said nothing was blocked; it lists the stop until a sync succeeds.
* The deliberate-refusal, systemic and changing-message guards pass before and after.
*
* PGLite here; Postgres through test/e2e/sync-entry-faults-6712-postgres.test.ts.
@@ -34,6 +36,7 @@ import { recordManagedSyncFailure } from '../src/core/persistence/sync-failures.
import { readGitSourceHolds } from '../src/core/persistence/sync-holds.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
import { readSyncStatus } from '../src/core/persistence/sync-status.ts';
+import { readBlockedManagedSyncs } from '../src/core/persistence/sync-blocked.ts';
import { managedBrain } from './helpers/managed-brain.ts';
import { testBackends } from './helpers/test-backends.ts';
@@ -209,4 +212,16 @@ for (const backend of testBackends()) describe(`[${backend}] GBRA-133: one odd f
expect((await recordManagedSyncFailure(engine, { ...base, invocation: 'three', observation_id: 'run-2:0:freeze:storage_error' })).failure).toMatchObject({ repeats: 3, attempts: 2 });
expect((await recordManagedSyncFailure(engine, { ...base, invocation: 'four', observation_id: 'run-3:0:freeze:storage_error', path: 'notes/other.md' })).failure).toMatchObject({ repeats: 1, attempts: 3 });
}), 240_000);
+ for (const [stop, point, path] of [['discovery', 'sync:level_read', '<discovery>'], ['entry', 'sync:mid_checkpoint', 'notes/odd.md']] as const) {
+ test(`S-61: doctor managed_sync_blocked lists a pass's ${stop} stop until a sync succeeds`, () => brain(async ({ engine, root }) => {
+ expect((await performManagedSync(engine, OPTS)).status).toBe('first_sync');
+ writeFileSync(join(root, 'notes/odd.md'), note('notes/odd')); commit(root, 'odd');
+ installFaultHook(at => { if (at === point) throw new Error('synthetic stop'); });
+ await expect(performManagedSync(engine, OPTS)).rejects.toThrow(`path=${path} code=storage_error: synthetic stop`);
+ expect(await readBlockedManagedSyncs(engine, ['default'])).toEqual([expect.objectContaining({ source_id: 'default', code: 'storage_error' })]);
+ installFaultHook(undefined);
+ expect((await performManagedSync(engine, OPTS)).status).toBe('synced');
+ expect(await readBlockedManagedSyncs(engine, ['default'])).toEqual([]);
+ }), 240_000);
+ }
});