Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
fix(serve): deferred embeds drain until done; --no-pull cost estimate never fetches (GBRA-133 2b.3)
garrytan086045184d2b
diff --git a/src/core/serve-sync-runner.ts b/src/core/serve-sync-runner.tsindex 1100bd58ab..2132d1860f 100644--- a/src/core/serve-sync-runner.ts+++ b/src/core/serve-sync-runner.ts@@ -123,10 +123,48 @@ interface DeferredEmbeds {timer?: ReturnType<typeof setTimeout>;stopped: boolean;unregister: () => void;+ /** Consecutive passes that failed (a provider error or failed chunks); picks the retry tier. */+ failures: number;+ /** Consecutive passes deferred because a delegated sync was running. */+ busy: number;}/** Each datastore owns its backlog and actual provider/SQL lifetime. */const deferredEmbeds = new Map<BrainEngine, DeferredEmbeds>();+/**+ * GBRA-133 2b.3: what the deferred-embed drain decided, oldest first (bounded), for tests and the serve log.+ * `retry` re-arms the drain after a pass left work (progress, a provider failure); `busy` defers while a delegated sync+ * runs, at most DEFERRED_EMBED_BUSY_MAX times in a row before `busy_override` drains beside it; `keyless` keeps the+ * backlog without a provider call or a timer.+ */+export type DeferredEmbedDecision = { decision: 'drained' | 'retry' | 'busy' | 'busy_override' | 'keyless'; delayMs?: number; failures?: number };+export const deferredEmbedDecisions: DeferredEmbedDecision[] = [];+const DEFERRED_EMBED_RETRY_TIERS = [1, 3, 12, 60];+const DEFERRED_EMBED_BUSY_MAX = 3;+let deferredEmbedBusyProbe: () => boolean = () => isDelegatedSyncRunning();++/** The retry unit: GBRAIN_DEFERRED_EMBED_RETRY_MS (default 5000; tiers 1x, 3x, 12x, 60x after failures). */+function deferredEmbedRetryMs(env: Record<string, string | undefined> = process.env): number {+ const raw = env.GBRAIN_DEFERRED_EMBED_RETRY_MS;+ const value = raw === undefined || raw === '' ? NaN : Number(raw);+ return Number.isFinite(value) && value >= 1 ? Math.floor(value) : 5_000;+}++function decideDeferredEmbed(entry: DeferredEmbedDecision): void {+ deferredEmbedDecisions.push(entry);+ if (deferredEmbedDecisions.length > 200) deferredEmbedDecisions.splice(0, deferredEmbedDecisions.length - 200);+}++function armDeferredEmbeds(engine: BrainEngine, state: DeferredEmbeds, delayMs: number): void {+ if (state.timer || state.stopped || shuttingDown) return;+ state.timer = setTimeout(() => {+ state.timer = undefined;+ if (state.stopped) return;+ void maybeDrainDeferredEmbeds(engine);+ }, delayMs);+ state.timer.unref?.();+}+const isTerminal = (s: DelegatedSyncState): boolean => s === 'done' || s === 'error';function log(msg: string): void {@@ -506,6 +544,11 @@ function ensureDrainerRegistered(): void {* wall clock; `pending` clears only when a run finds nothing left to embed,* so successive idle ticks converge on a fully-embedded brain. Keyless rule:* no embedding provider ⇒ leave pending (a later keyed serve drains it).+ * GBRA-133 2b.3: the drain re-arms itself until the backlog is gone: a pass+ * that left work retries after the retry unit, a failing provider backs off+ * through the tiers, and a sync backlog defers it at most+ * DEFERRED_EMBED_BUSY_MAX times before it drains beside the running sync, so+ * commit-triggered syncs (which always defer) never strand their embeddings.* Never throws.*/export async function maybeDrainDeferredEmbeds(engine: BrainEngine): Promise<void> {@@ -513,7 +556,16 @@ export async function maybeDrainDeferredEmbeds(engine: BrainEngine): Promise<voiif (!state || state.stopped || shuttingDown) return;if (state.running) return state.running;if (!state.pending.size) return;- if (isDelegatedSyncRunning()) return;+ if (deferredEmbedBusyProbe()) {+ if (state.busy < DEFERRED_EMBED_BUSY_MAX) {+ state.busy++;+ decideDeferredEmbed({ decision: 'busy', delayMs: deferredEmbedRetryMs() });+ armDeferredEmbeds(engine, state, deferredEmbedRetryMs());+ return;+ }+ decideDeferredEmbed({ decision: 'busy_override' });+ }+ state.busy = 0;const work = (async () => {const { companyBrainProfile, getCompanyBrainProfile } = await import('./company-brain/profile.ts');if (state.pending.has(undefined)) {@@ -524,8 +576,9 @@ export async function maybeDrainDeferredEmbeds(engine: BrainEngine): Promise<voifor (const source of [...state.pending]) if (source && await getCompanyBrainProfile(engine, source)) state.pending.delete(source);if (!state.pending.size) return;const { detectCapabilities } = await import('./capability.ts');- if (!detectCapabilities().embeddings.available) return;+ if (!detectCapabilities().embeddings.available) { decideDeferredEmbed({ decision: 'keyless' }); return; }const { runEmbedCore } = await import('../commands/embed.ts');+ let failed = false;// Snapshot one fair pass. A source queued again during its own provider// call stays pending, even when that earlier call reports no stale work.for (const sourceId of [...state.pending]) {@@ -535,11 +588,18 @@ export async function maybeDrainDeferredEmbeds(engine: BrainEngine): Promise<voiconst r = await runEmbedCore(engine, { stale: true, sourceId, signal: state.controller.signal, quiet: true });log(`embed-drain embedded=${r.embedded} failures=${r.failures} source=${sourceId ?? 'all'}`);if (r.embedded !== 0 || r.failures !== 0) state.pending.add(sourceId);+ if (r.failures !== 0) failed = true;} catch (error) {state.pending.add(sourceId);+ failed = true;log(`embed-drain failed: ${error instanceof Error ? error.message : String(error)}`);}}+ state.failures = failed ? state.failures + 1 : 0;+ if (!state.pending.size) { decideDeferredEmbed({ decision: 'drained' }); return; }+ const delayMs = deferredEmbedRetryMs() * DEFERRED_EMBED_RETRY_TIERS[Math.max(0, Math.min(state.failures, DEFERRED_EMBED_RETRY_TIERS.length) - 1)]!;+ decideDeferredEmbed({ decision: 'retry', delayMs, failures: state.failures });+ armDeferredEmbeds(engine, state, delayMs);})().catch(error => { log(`embed-drain failed: ${error instanceof Error ? error.message : String(error)}`); });state.running = work;try { await work; }@@ -551,7 +611,7 @@ export function scheduleDeferredSyncEmbeds(engine: BrainEngine, sourceId?: strinif (shuttingDown) return;let state = deferredEmbeds.get(engine);if (!state) {- state = { pending: new Set(), controller: new AbortController(), stopped: false, unregister: () => {} };+ state = { pending: new Set(), controller: new AbortController(), stopped: false, unregister: () => {}, failures: 0, busy: 0 };const owned = state;state.unregister = engine.registerBeforeDisconnect(async () => {owned.stopped = true;@@ -567,14 +627,7 @@ export function scheduleDeferredSyncEmbeds(engine: BrainEngine, sourceId?: strin}if (state.stopped) return;state.pending.add(sourceId);- if (state.timer) return;- const owned = state;- state.timer = setTimeout(() => {- owned.timer = undefined;- if (owned.stopped) return;- void maybeDrainDeferredEmbeds(engine);- }, 5_000);- state.timer.unref?.();+ armDeferredEmbeds(engine, state, 5_000);}/** Test seam: reset every module singleton (serial tests only). */@@ -587,6 +640,13 @@ export function __resetDelegatedSyncForTests(): void {if (state.timer) clearTimeout(state.timer);}deferredEmbeds.clear();+ deferredEmbedDecisions.length = 0;+ deferredEmbedBusyProbe = () => isDelegatedSyncRunning();+}++/** Test seam: stand in for "a delegated sync is running" (serial tests only; reset by __resetDelegatedSyncForTests). */+export function __setDeferredEmbedBusyProbeForTests(probe: () => boolean): void {+ deferredEmbedBusyProbe = probe;}/** Test seam: report whether the deferred-embed backlog is pending. */diff --git a/src/core/sync-cost-gate.ts b/src/core/sync-cost-gate.tsindex d271affd98..26b7e54ed7 100644--- a/src/core/sync-cost-gate.ts+++ b/src/core/sync-cost-gate.ts@@ -148,7 +148,7 @@ function estimateDeltaTokens(localPath: string, relPaths: string[]): number {* cost paid a few seconds early — a tighter cap would frequently fall back to* local HEAD and underestimate the remote delta).*/-function resolveEstimateTarget(localPath: string): { target: string; detached: boolean } | null {+function resolveEstimateTarget(localPath: string, noPull = false): { target: string; detached: boolean } | null {let head: string;try {head = git(localPath, ['rev-parse', 'HEAD']);@@ -164,7 +164,9 @@ function resolveEstimateTarget(localPath: string): { target: string; detached: b} catch {branch = null;}- if (branch && branch !== 'HEAD' && hasOriginRemote(localPath)) {+ // GBRA-133 2b.3: a --no-pull run syncs local HEAD and never fetches, so its estimate prices local HEAD and the gate+ // spends no network round trip (a fetch can take the shared 30 s git budget on a slow or unreachable remote).+ if (!noPull && branch && branch !== 'HEAD' && hasOriginRemote(localPath)) {try {// v0.42.42.0 (#2139): route through the SSRF-hardened fetch (same flags +// no-prompt env as pullRepo) — a cost preview / dry-run must NOT hit a@@ -232,7 +234,7 @@ export function estimateInlineNewTokens(chunker_version: string | null;}>,currentChunkerVersion: string,- opts: { forceFullTree?: boolean; chunkerDriftWalks?: boolean } = {},+ opts: { forceFullTree?: boolean; chunkerDriftWalks?: boolean; noPull?: boolean } = {},): InlineEstimate {let tokens = 0;let changedSources = 0;@@ -285,7 +287,7 @@ export function estimateInlineNewTokens(continue;}- const resolved = resolveEstimateTarget(localPath);+ const resolved = resolveEstimateTarget(localPath, opts.noPull === true);if (!resolved) {// HEAD unresolvable (not a git repo / gone) — can't compute a delta. CEILING.ceiling(localPath, strategy, 'git_unavailable');@@ -407,6 +409,8 @@ interface CostGateContext {yesFlag: boolean;full: boolean;includeGitignored?: boolean;+ /** The run will not pull: estimate against local HEAD without fetching. */+ noPull?: boolean;/** Message prefix ('sync --all' | 'sync'). */label: string;/** Public queue capability resolved at the command boundary. */@@ -550,6 +554,7 @@ export async function runInlineCostGate(// ── Inline path ───────────────────────────────────────────────const inline = estimateInlineNewTokens(sources, chunkerStamp(), {forceFullTree: ctx.includeGitignored === true,+ noPull: ctx.noPull === true,chunkerDriftWalks: full === true || !(await readManagedMode(engine).catch(() => false)),});// D7A: `--full` runs `performFullSync` → `runEmbedCore({stale:true})`, whichdiff --git a/src/core/sync-embed-backfill.ts b/src/core/sync-embed-backfill.tsindex 03b2336d4b..0ed145afb7 100644--- a/src/core/sync-embed-backfill.ts+++ b/src/core/sync-embed-backfill.ts@@ -33,6 +33,8 @@ type SyncCostGateFlags = {full: boolean;includeGitignored: boolean;noAutoEmbed: boolean;+ /** GBRA-133 2b.3: the run will not pull, so the inline estimate skips its remote fetch. */+ noPull?: boolean;};export async function resolveSyncAllEmbedPlan(@@ -73,6 +75,7 @@ export async function resolveSyncAllEmbedPlan(yesFlag: opts.yesFlag,full: opts.full,includeGitignored: opts.includeGitignored,+ noPull: opts.noPull,label: 'sync --all',workerSurface,autoSubmitEnabled: !opts.noAutoEmbed,@@ -104,6 +107,7 @@ export async function resolveSingleSyncEmbedPlan(yesFlag: opts.yesFlag,full: opts.full,includeGitignored: opts.includeGitignored,+ noPull: opts.noPull,label: 'sync',workerSurface,autoSubmitEnabled: !opts.noAutoEmbed,