Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(sync): connector partials exit 1 and print their real cause (#5012)
garrytandb832b5c350e
diff --git a/src/commands/sync-persistence-delegate.ts b/src/commands/sync-persistence-delegate.tsindex 3fdb2ae832..f453e07ff5 100644--- a/src/commands/sync-persistence-delegate.ts+++ b/src/commands/sync-persistence-delegate.ts@@ -71,7 +71,7 @@ export async function maybeDelegateSyncToPersistence(hostConfig:GBrainConfig|nulconsole.error('[sync] embeds deferred — the owner drains them using its configured provider and keys.');}}- if(result.managedWrite||result.status==='blocked_by_failures'||result.reason==='pull_failed')setCliExitVerdict(1);+ if(result.managedWrite||result.status==='blocked_by_failures'||result.reason==='pull_failed'||(await import('./sync/report.ts')).isFailedPartial(result))setCliExitVerdict(1);return true;}catch(error){if(error instanceof PersistenceIpcTransportError&&error.sent)error=new OperationError('write_pending','The sync acknowledgment was lost; accepted page requests retain their IDs.','Repeat the same sync options to resume the durable cursor.');diff --git a/src/commands/sync.ts b/src/commands/sync.tsindex db97eb054a..168bd6f578 100644--- a/src/commands/sync.ts+++ b/src/commands/sync.ts@@ -82,10 +82,10 @@ export interface SyncResult {** `files_imported` reflects ACTUAL persisted count (not the* not-yet-attempted set). `reason` distinguishes the partial cause so- * cron operators can disambiguate timeout vs pull-timeout in monitoring.+ * cron operators can disambiguate timeout vs pull-timeout in monitoring; connector item failures / early stop exit 1 (isFailedPartial).*/filesImported?: number;- reason?: 'timeout' | 'pull_timeout' | 'pull_failed' | 'stall_timeout' | 'checkpoint_unavailable' | 'writer_pending' | 'writer_yield';+ reason?: 'timeout' | 'pull_timeout' | 'pull_failed' | 'stall_timeout' | 'checkpoint_unavailable' | 'writer_pending' | 'writer_yield' | 'connector_item_failures' | 'connector_partial';/*** v0.42.x (#1794): cumulative file paths durably banked to the checkpoint* across THIS run + prior resumed runs. Surfaced on every partial/blockeddiff --git a/src/commands/sync/connector.ts b/src/commands/sync/connector.tsindex 4d5efc5652..fd805d84cb 100644--- a/src/commands/sync/connector.ts+++ b/src/commands/sync/connector.ts@@ -30,10 +30,27 @@ export async function runConnectorSync(engine: BrainEngine, opts: SyncOpts, manaconst options = signal ? { ...opts, signal } : opts;const fallbackDir = source.local_path ?? (managed ? '' : (await import('../../core/sources-ops.ts')).defaultCloneDir(`${sourceId}-${config.kind}`));serr(`[gbrain phase] sync.${config.kind}_materialize`);+ let result: SyncResult;if (config.kind === 'github') {const { parseGitHubSourceConfig, runGitHubSync } = await import('../../core/github-source.ts');- return runGitHubSync(engine, sourceId, parseGitHubSourceConfig(config, fallbackDir), options);+ result = await runGitHubSync(engine, sourceId, parseGitHubSourceConfig(config, fallbackDir), options);+ } else {+ const { parseGoogleSourceConfig, runGoogleSync } = await import('../../core/google/google-source.ts');+ result = await runGoogleSync(engine, sourceId, parseGoogleSourceConfig(config, fallbackDir), options);}- const { parseGoogleSourceConfig, runGoogleSync } = await import('../../core/google/google-source.ts');- return runGoogleSync(engine, sourceId, parseGoogleSourceConfig(config, fallbackDir), options);+ return withConnectorPartialReason(result, signal);+}++/**+ * #5012: a connector partial never reports the git path's `timeout` default.+ * Failed items name `connector_item_failures`; an early stop with no cause is+ * `connector_partial` unless the run's signal aborted it (`timeout`).+ */+export function withConnectorPartialReason(result: SyncResult, signal?: AbortSignal): SyncResult {+ if (result.status !== 'partial' || result.reason) return result;+ return {+ ...result,+ filesImported: result.filesImported ?? result.added + result.modified,+ reason: (result.failedFiles ?? 0) > 0 ? 'connector_item_failures' : signal?.aborted ? 'timeout' : 'connector_partial',+ };}diff --git a/src/commands/sync/report.ts b/src/commands/sync/report.tsindex 010e47abee..2253ad33bb 100644--- a/src/commands/sync/report.ts+++ b/src/commands/sync/report.ts@@ -19,6 +19,17 @@ export function shouldNudgeAfterSync(status: SyncResult['status']): boolean {return status === 'synced' || status === 'first_sync' || status === 'up_to_date';}+/**+ * #3068 / #5012: partials that do not converge on a plain retry exit+ * non-zero so cron and monitoring see them: a failed pull, connector items+ * that failed to import, and a connector that stopped early without a cause.+ * Timeout-class partials keep exit 0 (the next run continues).+ */+export function isFailedPartial(result: Pick<SyncResult, 'status' | 'reason'>): boolean {+ return result.status === 'partial'+ && (result.reason === 'pull_failed' || result.reason === 'connector_item_failures' || result.reason === 'connector_partial');+}+/*** Post-sync backup-coverage refresh (monthly, stale-only). The sync CLI is a* trusted local engine holder (D4), so the compute piggybacks here; the@@ -99,7 +110,8 @@ export function printSyncResult(result: SyncResult, sink: NodeJS.WriteStream = pif (result.uncommitted) writeUncommittedNote(result.uncommitted);break;case 'synced':- write(`Synced ${result.fromCommit?.slice(0, 8)}..${result.toCommit.slice(0, 8)}:`);+ // Connector sources have no commit range.+ write(result.toCommit ? `Synced ${result.fromCommit?.slice(0, 8) ?? '<initial>'}..${result.toCommit.slice(0, 8)}:` : 'Synced:');write(` +${result.added} added, ~${result.modified} modified, -${result.deleted} soft-deleted (recoverable 72h), R${result.renamed} renamed`);write(` ${result.chunksCreated} chunks created${result.embedded > 0 ? `, ${result.embedded} pages embedded` : ''}`);if (result.uncommitted) writeUncommittedNote(result.uncommitted);@@ -145,6 +157,22 @@ export function printSyncResult(result: SyncResult, sink: NodeJS.WriteStream = pwrite(` Fix the pull (see the warning above), then re-run 'gbrain sync' (last_commit unchanged; safe to retry).`);break;}+ if (result.reason === 'connector_item_failures') {+ write(+ `Sync PARTIAL [connector_item_failures]: ${result.failedFiles ?? 0} connector item(s) failed to import; ` ++ `${result.filesImported ?? result.added + result.modified} page(s) written.`,+ );+ write(` The failure reasons are in the warnings above. Fix the cause, then re-run 'gbrain sync --source <id>' (the cursor did not advance past failed items; see 'gbrain sources status <id>'). Docs: docs/guides/google-connect.md#held-items`);+ break;+ }+ if (result.reason === 'connector_partial') {+ write(+ `Sync PARTIAL [connector_partial]: the connector stopped before finishing and reported no cause; ` ++ `${result.filesImported ?? result.added + result.modified} page(s) written.`,+ );+ write(` Check the warnings above (expired or revoked credentials print there), fix the cause, then re-run 'gbrain sync --source <id>'.`);+ break;+ }// v0.41.13.0 (T7 / D-V3-5): --timeout fired before the bookmark write// so last_commit is UNCHANGED. The next sync re-walks the same diff// and content_hash short-circuits already-imported files at ~10ms each.diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.tsindex a3dda689cb..61e0acf6d7 100644--- a/src/commands/sync/run.ts+++ b/src/commands/sync/run.ts@@ -30,6 +30,7 @@ import {maybeBackupCoverageRefresh,printSyncResult,shouldNudgeAfterSync,+ isFailedPartial,} from './report.ts';import { runSyncTrigger } from './trigger.ts';@@ -526,7 +527,7 @@ async function runSyncAll(// green exit would hide it from cron/monitoring. Timeout-class partials// keep the pre-existing exit-0 behavior (they converge on retry).const pullFailedCount = perSourceResults.filter(- (r) => r.status === 'ok' && r.result?.status === 'partial' && r.result.reason === 'pull_failed',+ (r) => r.status === 'ok' && r.result && isFailedPartial(r.result),).length;if (errCount > 0 || pullFailedCount > 0) process.exit(1);return;@@ -782,7 +783,7 @@ async function runSingleSourceSync(// Routed through the owned verdict channel (NOT bare `process.exitCode`,// which PGLite's Emscripten runtime clobbers mid-run — see// src/core/cli-force-exit.ts).- if (result.managedWrite || result.status === 'blocked_by_failures' || (result.status === 'partial' && result.reason === 'pull_failed')) {+ if (result.managedWrite || result.status === 'blocked_by_failures' || isFailedPartial(result)) {const { setCliExitVerdict } = await import('../../core/cli-force-exit.ts');setCliExitVerdict(1);}diff --git a/src/core/github-source.ts b/src/core/github-source.tsindex ded3669a10..78d5fcfac9 100644--- a/src/core/github-source.ts+++ b/src/core/github-source.ts@@ -1483,5 +1483,10 @@ function syncResult(embedded: summary.embedded,pagesAffected: summary.pagesAffected,...(summary.failedFiles > 0 ? { failedFiles: summary.failedFiles } : {}),+ // #5012: a partial sweep names its real cause and counts what it wrote.+ ...(summary.status === 'partial' ? {+ filesImported: summary.added + summary.modified,+ reason: summary.failedFiles > 0 ? 'connector_item_failures' as const : opts.signal?.aborted ? 'timeout' as const : 'connector_partial' as const,+ } : {}),};}diff --git a/test/github-source-materialize.test.ts b/test/github-source-materialize.test.tsindex a8642dc14c..2f1b789484 100644--- a/test/github-source-materialize.test.ts+++ b/test/github-source-materialize.test.ts@@ -382,6 +382,9 @@ describe('github-source materialize', () => {);expect(res.status).toBe('partial');expect(res.failedFiles).toBeGreaterThan(0);+ // #5012: the partial names its real cause, never the git path's timeout default.+ expect(res.reason).toBe('connector_item_failures');+ expect(res.filesImported).toBe(res.added + res.modified);expect(readFileSync(join(dir, 'gh', REPO, '3.md'), 'utf-8')).toBe(oldPage);const state = JSON.parse(readFileSync(join(dir, '.github-source.json'), 'utf-8')) as { last_sweep_at: string };expect(state.last_sweep_at).toBe('2026-08-02T00:00:00Z');diff --git a/test/sync-connector-partial-exit.test.ts b/test/sync-connector-partial-exit.test.tsnew file mode 100644index 0000000000..c759f45ad6--- /dev/null+++ b/test/sync-connector-partial-exit.test.ts@@ -0,0 +1,69 @@+/**+ * #5012 (non-Google half) — connector partial syncs exit non-zero and print+ * their real cause. Pre-fix a GitHub sweep with a failed item returned+ * `partial` with no `reason`/`filesImported`, so the CLI printed+ * "imported 0 of N file(s), reason=timeout" and exited 0; a cron wrapper+ * could not tell it from a clean run.+ */+import { describe, expect, test } from 'bun:test';+import { isFailedPartial, printSyncResult } from '../src/commands/sync/report.ts';+import { withConnectorPartialReason } from '../src/commands/sync/connector.ts';+import type { SyncResult } from '../src/commands/sync.ts';++const base: SyncResult = {+ status: 'partial', fromCommit: null, toCommit: '', added: 12, modified: 3, deleted: 0, renamed: 0,+ chunksCreated: 0, embedded: 0, pagesAffected: [],+};++function render(result: SyncResult): string {+ let out = '';+ printSyncResult(result, { write: (s: string) => { out += s; return true; } } as unknown as NodeJS.WriteStream);+ return out;+}++describe('#5012 connector partial reason', () => {+ test('failed items -> connector_item_failures with the written count', () => {+ const r = withConnectorPartialReason({ ...base, failedFiles: 1 });+ expect(r.reason).toBe('connector_item_failures');+ expect(r.filesImported).toBe(15);+ });++ test('an early stop with no cause -> connector_partial; an aborted run stays timeout', () => {+ expect(withConnectorPartialReason(base).reason).toBe('connector_partial');+ const ac = new AbortController();+ ac.abort();+ expect(withConnectorPartialReason(base, ac.signal).reason).toBe('timeout');+ });++ test('a reason the connector already named is kept', () => {+ expect(withConnectorPartialReason({ ...base, reason: 'timeout' }).reason).toBe('timeout');+ expect(withConnectorPartialReason({ ...base, status: 'synced' }).reason).toBeUndefined();+ });+});++describe('#5012 exit verdict', () => {+ test('connector partials and pull failures exit non-zero; timeouts keep exit 0', () => {+ expect(isFailedPartial({ status: 'partial', reason: 'connector_item_failures' })).toBe(true);+ expect(isFailedPartial({ status: 'partial', reason: 'connector_partial' })).toBe(true);+ expect(isFailedPartial({ status: 'partial', reason: 'pull_failed' })).toBe(true);+ expect(isFailedPartial({ status: 'partial', reason: 'timeout' })).toBe(false);+ expect(isFailedPartial({ status: 'synced' })).toBe(false);+ });+});++describe('#5012 printed result', () => {+ test('connector partial names the cause and the recovery, never reason=timeout', () => {+ const out = render(withConnectorPartialReason({ ...base, failedFiles: 2 }));+ expect(out).toContain('[connector_item_failures]');+ expect(out).toContain('2 connector item(s) failed');+ expect(out).toContain('15 page(s) written');+ expect(out).toContain("gbrain sync --source <id>");+ expect(out).not.toContain('reason=timeout');+ });++ test('a connector sync with no commit range prints Synced:, never undefined', () => {+ const out = render({ ...base, status: 'synced' });+ expect(out.split('\n')[0]).toBe('Synced:');+ expect(out).not.toContain('undefined');+ });+});