Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

sync: inherit processing opt-outs, hand authority over on adoption, drop explicitProcessing (#6712 PR 1)

garrytan5aa2185888cc
diff --git a/src/commands/sync-delegate.ts b/src/commands/sync-delegate.ts
index ba678ae6ef..a527e65632 100644
--- a/src/commands/sync-delegate.ts
+++ b/src/commands/sync-delegate.ts
@@ -62,7 +62,6 @@ import {
} from '../core/context/resolve-ipc.ts';
import {
DELEGATED_SYNC_LANES_MAX,
- DELEGATED_SYNC_PROCESSING_KEYS,
type DelegatedSyncOptions,
type SyncStartRegistration,
type SyncStatusResponse,
@@ -146,8 +145,6 @@ export function parseDelegatedSyncArgs(args: string[]): ParsedDelegatedArgs {
// --all, --watch, --exclude, --workers, …) and anything future.
return { ok: false, refused: tok };
}
- // #6696: always sent, so a flagless run adopts an unfinished cursor's options on the serve as it does in-process.
- options.explicitProcessing = (['noEmbed', 'noExtract', 'noSchemaPack'] as const).filter(key => options[key] === true);
return { ok: true, options: options as Omit<DelegatedSyncOptions, 'timeoutSeconds'>, explicitSource };
}
@@ -586,8 +583,6 @@ export async function maybeDelegateManagedSyncToServe(engine: BrainEngine, args:
sourceId, timeoutSeconds, origin: 'interactive',
...pick(opts, ['dryRun', 'full', 'noPull', 'noEmbed', 'noExtract', 'noSchemaPack', 'skipFailed', 'retryFailed', 'includeGitignored', 'noBulk'] as const),
...(opts.lanes !== undefined ? { lanes: opts.lanes } : {}),
- // #6696: an empty list crosses the wire (a flagless run adopts the cursor's options); a caller that set none is strict, as in-process.
- explicitProcessing: [...opts.explicitProcessing ?? DELEGATED_SYNC_PROCESSING_KEYS],
// Sent only when set, so a serve that predates the field keeps accepting every run without a deferral.
...(opts.embedDeferred ? { embedDeferred: true } : {}),
};
diff --git a/src/commands/sync.ts b/src/commands/sync.ts
index d2c96419a2..eac863b596 100644
--- a/src/commands/sync.ts
+++ b/src/commands/sync.ts
@@ -23,6 +23,16 @@ export interface SyncResult {
retryWait?: import('../core/persistence/sync-run.ts').RetryWait;
/** #6712 PR 1: another drainer holds (or took) the source's drain lease; `resumable`, nothing admitted by this run. */
leaseHeld?: import('../core/persistence/sync-lease.ts').DrainLeaseHeld;
+ /**
+ * #6712 PR 1 (#6552 §1): processing opt-outs this run kept from the unfinished cursor it resumed though the caller did
+ * not set them (`gbrain embed --stale` / `gbrain extract --stale` settle the pages they skipped).
+ */
+ inherited_options?: Array<'noEmbed' | 'noExtract' | 'noSchemaPack'>;
+ /** #6712 PR 1: this run finished a cursor another writer, or an older key, started, under that run's frozen options (shown to local callers). */
+ cursorAdopted?: { writer_changed: boolean; legacy_key: boolean; sync_options?: import('../core/persistence/sync-prepare.ts').SyncCursorOptions | null;
+ processing_options?: import('../core/persistence/sync-authority.ts').SyncProcessingOptions | null };
+ /** #6712 PR 1: older-key cursors of the incarnation this run's fan-in folded (`retained`: left while a request under them is open). */
+ cursorFanIn?: { adopted: boolean; superseded: number; retained: number };
/** #6643: knock-on pages this run re-froze automatically, and the limits that bound it. */
/** #6693: caller remembers refused while their page's file awaited import (or was held), replayed after this sync imported it. */
replayedRemembers?: import('../core/repair/failed-writes.ts').ImportReplayReport;
@@ -180,8 +190,6 @@ export interface SyncOpts {
noSchemaPack?: boolean;
/** #6696 (A7): server-only; the drain's first pass checks the run's estimated receipts against the capacity left before admitting. */
capacityPreflight?: boolean;
- /** Processing options this caller set; an unfinished managed cursor supplies the rest (unset = all explicit). */
- explicitProcessing?: Array<'noEmbed' | 'noExtract' | 'noSchemaPack'>;
/** #6696: a runtime paid-work constraint (the cost gate deferred this run's embedding); never a processing option, never lifted by cursor adoption. */
embedDeferred?: boolean;
/**
diff --git a/src/commands/sync/run.ts b/src/commands/sync/run.ts
index 5066405d16..c8de79ddb8 100644
--- a/src/commands/sync/run.ts
+++ b/src/commands/sync/run.ts
@@ -5,8 +5,6 @@ import { slog, withSourcePrefix } from '../../core/console-prefix.ts';
import type { BrainEngine } from '../../core/engine.ts';
import { msysToNativePath } from '../../core/path-confine.ts';
import { syncFailureJsonFields, readManagedSyncFailures } from '../../core/persistence/sync-failures.ts';
-import { formatManagedRetryAction, managedRetryActions } from '../../core/persistence/managed-retry-actions.ts';
-import { managedSyncCursorKey } from '../../core/persistence/sync-run.ts';
import { syncHoldJsonFields } from '../../core/persistence/sync-holds.ts';
import { printHoldNotes } from '../sync-diagnostics.ts';
import { getDefaultSourcePath } from '../../core/source-resolver.ts';
@@ -335,7 +333,7 @@ async function runSyncAll(
input: { noEmbed: boolean; embeddingCredentialError: Error | undefined; resumeCommand: string },
): Promise<void> {
const {
- dryRun, full, noPull, noBulk, lanes, noExtract, skipFailed, retryFailed, noSchemaPack, explicitProcessing, includeGitignored,
+ dryRun, full, noPull, noBulk, lanes, noExtract, skipFailed, retryFailed, noSchemaPack, includeGitignored,
workingTree, missingPathMode, jsonOut, yesFlag, serialFlag, noAutoEmbed, maxSources, concurrency, timeoutSeconds,
} = flags;
const { noEmbed, embeddingCredentialError, resumeCommand } = input;
@@ -509,7 +507,7 @@ async function runSyncAll(
// #6696: a planned or cost-gate deferral (not the user's --no-embed) survives cursor adoption.
embedDeferred: effectiveNoEmbed && !noEmbed,
noExtract,
- skipFailed, retryFailed, noSchemaPack, explicitProcessing,
+ skipFailed, retryFailed, noSchemaPack,
includeGitignored,
workingTree,
sourceId: src.id,
@@ -772,7 +770,7 @@ async function runSingleSourceSync(
): Promise<void> {
const {
repoPath, watch, interval, dryRun, full, noPull, noBulk, lanes, noExtract, skipFailed, retryFailed, resetCheckpoint, noSchemaPack,
- explicitProcessing, includeGitignored, workingTree, jsonOut, yesFlag, noAutoEmbed, strategyArg, srcSubpath,
+ includeGitignored, workingTree, jsonOut, yesFlag, noAutoEmbed, strategyArg, srcSubpath,
excludePatterns, includeHiddenPatterns, concurrency, timeoutSeconds,
} = flags;
const { sourceId, companyPolicy, noEmbed, resumeCommand, args } = input;
@@ -792,7 +790,7 @@ async function runSingleSourceSync(
const singleSourceInterrupt = new AbortController();
const onSingleSourceSigint = () => { try { singleSourceInterrupt.abort(new Error('SIGINT')); } catch { /* */ } };
const opts: SyncOpts = {
- repoPath, dryRun, full, noPull, noEmbed, noExtract, skipFailed, retryFailed, resetCheckpoint, noSchemaPack, explicitProcessing, includeGitignored, workingTree, sourceId,
+ repoPath, dryRun, full, noPull, noEmbed, noExtract, skipFailed, retryFailed, resetCheckpoint, noSchemaPack, includeGitignored, workingTree, sourceId,
strategy: strategyArg, concurrency,
srcSubpath,
exclude: excludePatterns.length > 0 ? excludePatterns : undefined,
@@ -844,25 +842,21 @@ async function runSingleSourceSync(
// v0.42.42.0 (#2139, D13C): scope the retry count to THIS source — rows
// carry source_id (#1939), so a single-source retry shouldn't report
// another source's failures.
- // A managed retry resumes only the cursor its own options select; failures under other options are named, not counted.
+ // #6712 PR 1: a managed source has one cursor, whatever options a run passes, so every recorded failure is this retry's.
const managedBrain = await readManagedMode(engine);
let failures: Array<{ source_id: string }> = unacknowledgedSyncFailures().filter(f => f.source_id === sourceId);
- if (managedBrain) {
- const managed = await readManagedSyncFailures(engine, [sourceId]);
- const key = await managedSyncCursorKey(engine, opts).catch(() => null);
- const other = key ? managed.filter(f => f.cursor_key !== key) : [];
- failures = key ? managed.filter(f => f.cursor_key === key) : managed;
- if (other.length) {
- slog(`${other.length} previously-failed file(s) of this source belong to a run with different sync options and are not retried by this invocation. Each, with the action that settles it:`);
- for (const action of await managedRetryActions(engine, opts, other)) slog(` ${formatManagedRetryAction(action)}`);
- }
- }
+ if (managedBrain) failures = await readManagedSyncFailures(engine, [sourceId]);
const legacyRows = managedBrain ? legacyLedgerRows(sourceId).length : 0;
if (legacyRows) slog(`${legacyRows} legacy ledger row(s) of this source were recorded by the pre-managed sync and are not retried by a managed sync; this run settles every one whose file it imports.`);
if (failures.length === 0) {
slog(legacyRows ? 'No managed sync failures recorded; checking the durable sync cursor for unfinished or failed writes.' : 'No local ledger entries; checking the durable sync cursor for unfinished or failed writes.');
} else {
slog(`Retrying ${failures.length} previously-failed file(s)...`);
+ // #6712 PR 1: a failure whose run no cursor holds any more (an older gbrain's, under its own key) is not settled by
+ // a sync; the orphan repair retires it.
+ const orphaned = managedBrain ? (await (await import('../../core/persistence/managed-sync-orphans.ts')).classifyManagedSyncOrphans(engine, [sourceId]))
+ .orphans.filter(orphan => orphan.kind === 'failure_row').length : 0;
+ if (orphaned) slog(`${orphaned} of them belong to no sync run any more (an older gbrain's run under another cursor key); no sync settles them: preview and retire them with gbrain repair managed-sync-orphans --source ${sourceId}.`);
}
}
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 6952c649ff..97149d97f0 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -634,6 +634,12 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText }
{ since: '0.60.245.0', text: 'A write refused because its page\'s canonical file holds a committed Git change that managed sync has not imported yet now says so (`source_changed`, reason `pending_import`, "The canonical file holds a committed Git change that sync has not imported yet.") instead of "an uncoordinated local edit". A `remember` refused that way, or refused because sync held the file, is kept: after each managed sync, gbrain replays those remembers whose page now matches its file, once, with the fact\'s original date and the caller\'s original authority (at most 50 per sync; the sync result\'s `replayedRemembers` counts them), so the agent should not save the fact again. `put_page` and other writes are not replayed: resubmit after the next sync. Remembers refused before this release are listed by `gbrain repair failed-writes --source <id>`.' },
// #6686 (D8): a facts fence below the timeline sentinel.
{ since: '0.60.245.0', text: 'A page whose only `## Facts` fence sits below the timeline sentinel keeps it there: `remember` and `extract_facts` now add their rows to that fence (and strike a replaced row where it lives) instead of adding a second fence above the sentinel, and `extract_facts` reconciles such a fence instead of warning `FACTS_FENCE_BELOW_SENTINEL` and freezing its facts. A page that already has a fence on each side of the sentinel still warns, now naming `gbrain repair split-facts --source <id>`, an explicit preview-then-apply repair that merges the two fences under their own row numbers and refuses a page whose fences share a row number.' },
+ { since: '0.60.249.0', text: 'A managed source now has one drainer at a time (#6712): every managed sync pass (the CLI, `--no-delegate` included, a serve, a `sync` job, the dream cycle) runs under the source\'s drain lease, a 2-minute lease renewed every 20 s, so a crashed holder\'s lease lapses within one cron tick. A second `gbrain sync` follows the holder within its own `--timeout`, printing the holder (kind, pid, host, version) and the pages it commits, and takes over when the holder finishes; out of budget it exits 0 `resumable` with code `sync_drain_lease_held`, `next.retry_after_ms` 60 s and `safe_to_loop`. Ctrl-C stops following and leaves the holder running. A `sync` job or the cycle that finds the lease held skips, as it did on the sync lock.' },
+ { since: '0.60.249.0', text: 'A `gbrain sync` that follows another drainer no longer exits 0 forever behind a wedged one: when the lease holder commits no page and saves no cursor for 5 minutes, the run stops `blocked` (exit 1) with `drain_stalled`, cause `no_progress`, `drain.stall.lease_holder` naming the holder, and a fix that reads `gbrain sources writer status --source <id> --json` and names `gbrain sync --source <id> --no-pull --break-lock` for a holder that is gone.' },
+ { since: '0.60.249.0', text: 'A managed source keeps one sync cursor (#6712): the cursor key is the source incarnation (plus the company, for a company approval) instead of a digest of the writer, its authority and the options, so a CLI run, a serve, a job and a different writer all resume the same cursor. An unfinished cursor an older gbrain left under another key is finished in place under that key and reported in `cursorAdopted`; other old-key cursors are retired (`superseded_by_adoption`, queued requests cancelled) once nothing under them is running, and a run waits (`writer_pending`) for a request still running under one before it publishes. `cursorFanIn` counts them.' },
+ { since: '0.60.249.0', text: 'Resuming an unfinished managed sync never refuses over processing options any more (#6712): the cursor\'s `--no-embed`, `--no-extract` and `--no-schema-pack` opt-outs are inherited by every run that resumes it, a flag that would have asked for more processing is reported in `inherited_options` (and printed), and `cursor_processing_options_conflict` is no longer returned. A writer that resumes another writer\'s cursor admits the rest under its own validated grant; requests already admitted stay under their original principal, are read and cancelled under it, and are never rewritten.' },
+ { since: '0.60.249.0', text: 'The delegation wire\'s `explicitProcessing` field is accepted from a sync client below 0.60.249.0 and ignored until 2026-11-14 (`WIRE_SKEW_WINDOWS` in `src/core/wire-skew.ts`), then removed. `gbrain sync --retry-failed` on a managed source now counts every failure of the source, since no failure sits under another cursor key.' },
+ { since: '0.60.249.0', text: 'Downgrading below 0.60.249.0 must be quiescent: stop `gbrain serve`, autopilot and sync crons, let the running sync finish, then downgrade. An older binary does not take the drain lease; while a newer non-job holder drains, it writes a `gbrain-drain-lease` row that the live-sync check of 0.60.231.0 and later sees, so such an autopilot backs off instead of dispatching a second sync, but an older CLI started beside a newer drainer is not fenced. An older gbrain resumes an old-key cursor only; a cursor this release created under the new key is invisible to it and is rediscovered from the last synced commit.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/context/sync-ipc.ts b/src/core/context/sync-ipc.ts
index c50c0feab3..5676b3d0b3 100644
--- a/src/core/context/sync-ipc.ts
+++ b/src/core/context/sync-ipc.ts
@@ -88,8 +88,6 @@ export interface DelegatedSyncOptions {
lanes?: number;
/** #6696 (A5): who the run's writes are for; the operator's CLI sends `interactive`, absent is `background`. */
origin?: 'interactive' | 'background';
- /** #6317: the processing options the caller set itself; the managed cursor supplies the rest. #6696: a missing list (an older CLI) means none. */
- explicitProcessing?: Array<typeof DELEGATED_SYNC_PROCESSING_KEYS[number]>;
/** #6696: the client's cost gate deferred this run's embedding; cursor adoption never lifts it. Sent only when true. */
embedDeferred?: boolean;
/**
@@ -142,6 +140,8 @@ export function validateDelegatedSyncOptions(raw: unknown): DelegatedSyncValidat
if (keys.length > DELEGATED_SYNC_PROCESSING_KEYS.length || keys.some(key => !(DELEGATED_SYNC_PROCESSING_KEYS as readonly string[]).includes(key))) {
return { ok: false, error: 'invalid_options:explicitProcessing' };
}
+ // #6712 PR 1: accepted from an older CLI and ignored (WIRE_SKEW_WINDOWS.explicitProcessing); the cursor's opt-outs are inherited.
+ delete out.explicitProcessing;
}
if (out.origin !== undefined && out.origin !== 'interactive' && out.origin !== 'background') {
return { ok: false, error: 'invalid_options:origin' };
diff --git a/src/core/persistence/sync-administration.ts b/src/core/persistence/sync-administration.ts
index d871e36043..ca75de5891 100644
--- a/src/core/persistence/sync-administration.ts
+++ b/src/core/persistence/sync-administration.ts
@@ -5,7 +5,6 @@ import { currentVerifiedLocalWriter } from './identity.ts';
import { submissionAuthority } from './authority.ts';
import type { OperationContext } from '../ops/contract.ts';
import { validateSyncWireParams } from './sync-wire.ts';
-import { typedSyncProcessing } from './sync-authority.ts';
import { readManagedMode } from './managed-mode.ts';
import { trustedCliRequired } from '../ops/op-fix.ts';
@@ -39,7 +38,7 @@ export async function runAuthenticatedSyncSlice(engine: BrainEngine, params: Rec
return {...result,source_id:sourceId};
}
const {performManagedSync}=await import('./sync-run.ts');
- return {...await performManagedSync(engine,{...wire.options,sourceId,explicitProcessing:wire.options.explicitProcessing??typedSyncProcessing(wire.options),signal:controller.signal},{maxPages:25,maxMs:1000}),source_id:sourceId};
+ return {...await performManagedSync(engine,{...wire.options,sourceId,signal:controller.signal},{maxPages:25,maxMs:1000}),source_id:sourceId};
})();
return await work;
} finally {if(timer)clearTimeout(timer);unregister();}
diff --git a/src/core/persistence/sync-authority.ts b/src/core/persistence/sync-authority.ts
index ff3cb7a170..da4758ba36 100644
--- a/src/core/persistence/sync-authority.ts
+++ b/src/core/persistence/sync-authority.ts
@@ -36,14 +36,6 @@ export function syncProcessingOptions(opts: SyncOpts): SyncProcessingOptions {
return { noEmbed: opts.noEmbed === true, noExtract: opts.noExtract === true, noSchemaPack: opts.noSchemaPack === true };
}
export const SYNC_PROCESSING_KEYS = ['noEmbed', 'noExtract', 'noSchemaPack'] as const;
-/** The processing options a caller set itself; an unfinished cursor supplies the rest (#5632). */
-export function explicitSyncProcessing(values: Record<string, unknown>): Array<keyof SyncProcessingOptions> {
- return SYNC_PROCESSING_KEYS.filter(key => typeof values[key] === 'boolean');
-}
-/** #6696: the processing flags a payload without an explicit list set: an older client sends true for each one typed, nothing for the rest. */
-export function typedSyncProcessing(values: Partial<Record<keyof SyncProcessingOptions, unknown>>): Array<keyof SyncProcessingOptions> {
- return SYNC_PROCESSING_KEYS.filter(key => values[key] === true);
-}
export function assertSyncDispatchActive(): void {
assertSourceFilesystemActive(true);
throwIfAborted(currentJobSignal());
@@ -132,7 +124,7 @@ export function validateManagedSyncOptions(opts: SyncOpts): void {
const current = currentSubmissionAuthority();
if (current?.kind !== 'remote_generic') return;
// #6706: the worker's own drain controls (never read from a remote job's data) bound the run; they cannot widen what it writes.
- const allowed = new Set(['repoPath','sourceId','noPull','noEmbed','noExtract','explicitProcessing','signal','concurrency','onProgress','auto_embed_backfill',
+ const allowed = new Set(['repoPath','sourceId','noPull','noEmbed','noExtract','drainHolder','signal','concurrency','onProgress','auto_embed_backfill',
'drain','deadlineAtMs','drainStartedAt','bulk','lanes','capacityPreflight']);
if (current.grant.jobName !== 'sync' || opts.repoPath !== current.grant.canonicalRoot || opts.sourceId !== current.grant.sourceId ||
opts.noPull !== true || opts.noEmbed !== true || opts.noExtract !== true ||
diff --git a/src/core/persistence/sync-run.ts b/src/core/persistence/sync-run.ts
index 969db5f4a6..c5998483e3 100644
--- a/src/core/persistence/sync-run.ts
+++ b/src/core/persistence/sync-run.ts
@@ -16,7 +16,7 @@ import { isWriteCapacityWait, retryWriteAdmission } from './admission-retry.ts';
import { assertPersistenceAccepting, awaitWrite, foregroundWriteCompletions, startPersistenceConsumer } from './service.ts';
import { assertSyncEntryOrigin, discoverManagedSync, resolveManagedSyncContext, readSyncFile, syncGit, type ManagedSyncContext, type SyncDiscovery } from './sync-discovery.ts';
import { slugModeCheckpointRevivable } from './sync-slug-mode.ts';
-import { selectManagedCursor } from './sync-cursor-key.ts';
+import { managedCursorKey, resolveManagedCursor } from './sync-cursor-key.ts';
import { isImageFilePath, isMultimodalEnabled } from '../sync.ts';
import { assertSyncPageOrigin, sameSyncOrigin, syncOriginScope } from './sync-origin.ts';
import { assertManagedSyncActive, assertSyncDispatchActive, managedSyncAuthority, validateSyncAuthority, validateManagedSyncOptions, syncProcessingOptions, SYNC_PROCESSING_KEYS, type SyncAuthority, type SyncProcessingOptions } from './sync-authority.ts';
@@ -35,12 +35,12 @@ import { writeFailureDiagnostic } from './verb-errors.ts';
import { extractManagedStaleLinks } from './links-maintenance.ts';
import { addSettledRange, CHECKPOINT_VALIDATION_TIMEOUT, checkpointRetryCommand, checkpointTimeoutHint, findIncompleteSyncReceipt, type SyncSettledIndexes } from './checkpoint-validation.ts';
import { isTerminalWriteState, publicWriteReceipt, type WriteReceipt } from './types.ts';
-import { principalKey, type WriteRequest } from './model.ts';
+import { principalKey, type Principal, type WriteRequest } from './model.ts';
import { readJournalLimits } from './limits.ts';
import { assertManagedSyncAllowed } from './worktree-refresh.ts';
import type { GBrainConfig } from '../config.ts';
import { admitGroup, freezeFollowers, groupableIntent, nextGroupSize, type BulkSettings } from './sync-group.ts';
-import { cancelRowsUnderCursor, cancelWindow } from './sync-window.ts';
+import { cancelRowsUnderCursor, cancelWindow, type CursorFence } from './sync-window.ts';
import { cursorFenceCause, isSyncKnockOn, knockOnDetail, knockOnRoot } from './sync-knock-on.ts';
import { managedSyncResumeArgs } from '../sync-reconcile.ts';
import { laneApplyMsPerMember, lanePolicy, openLanes } from './sync-lanes.ts';
@@ -55,6 +55,7 @@ import { checkpointSuperseded } from './sync-checkpoint-replaced.ts';
import { publicFailureDetail } from './publication-failure.ts';
import { fileChangedAfterAdmission, headCommittedBytes, originFaultHold, pageChangeProof, pageChangedHold, pinnedWorktreeConflict, receiptPageFaultHold, worktreeDirtyHold } from './sync-page-fault.ts';
import { faultPoint } from './fault-points.ts';
+import { syncCursorOptions } from './sync-slices.ts';
import { pipelined } from '../page-state/transactions.ts';
import { withCoordinatedWrite } from './context.ts';
import { principalAttribution } from './attribution.ts';
@@ -471,23 +472,87 @@ async function freezeEntry(engine: BrainEngine, cursor: Cursor, key: string, ass
policyFingerprint: currentCompanyBrainSync(cursor.sourceId)!.policyFingerprint } } : {}) } });
}
-/** A resume adopts the cursor's stored processing options unless the caller set a conflicting one explicitly. */
-function assertCursorProcessingOptions(cursor: Cursor, processingOptions: SyncProcessingOptions, explicitProcessing: SyncOpts['explicitProcessing']): void {
+/**
+ * #6712 PR 1: a pass resumes the source's one cursor whoever wrote it (sync-cursor-key.ts), in one compare-and-swap:
+ * - Admitted requests keep the authority frozen in their intent: they are read under that principal (`admittedBy`) and
+ * publish under it. A frozen entry no request was admitted for yet is dropped (`withoutUnadmitted`), so it is frozen
+ * again under this pass's authority and nothing new is admitted on an earlier writer's grant.
+ * - This pass's authority is validated and stamped on the cursor in the same transaction; what it freezes from then on
+ * is authorized for its own grant (`freezeEntry` validates every entry with the cursor's authority).
+ * - A remote caller resumes only its own principal's cursor; any other is left to the brain host's CLI.
+ * - Processing opt-outs: a flagless resume keeps the cursor's accepted ones (`inherited`); a flag the caller set adds
+ * its opt-out to the requests frozen from now on. Admitted requests keep their frozen options, and a company approval
+ * keeps its exact options.
+ */
+async function adoptCursor(engine: BrainEngine, key: string, cursor: Cursor, input: { authority: SyncAuthority; processingOptions: SyncProcessingOptions;
+ embedDeferred?: boolean; assertActive: () => void }): Promise<{ cursor: Cursor; inherited: Array<keyof SyncProcessingOptions>; writerChanged: boolean }> {
+ const { authority } = input;
+ // #6696: a cost-gate deferral is this run's constraint (each request it freezes carries `embedDeferred`), never an opt-out the cursor keeps.
+ const processingOptions = input.embedDeferred ? { ...input.processingOptions, noEmbed: false } : input.processingOptions;
+ const writerChanged = digest(cursor.authority) !== digest(authority);
+ if (writerChanged && authority.writer.remote && (!cursor.authority.writer.remote
+ || principalKey(cursor.authority.writer.principal) !== principalKey(authority.writer.principal))) throw localResumeRequired(cursor.sourceId);
const stored = cursor.processingOptions;
- if (stored ? digest(stored) !== digest(processingOptions) : !cursor.pending) {
- // An unattended or flagless resume adopts the cursor's options; freezeEntry reads them from the cursor.
- const explicit = explicitProcessing ?? SYNC_PROCESSING_KEYS;
- if (!stored || explicit.some(key => stored[key] !== processingOptions[key])) {
- const flags = { noEmbed: '--no-embed', noExtract: '--no-extract', noSchemaPack: '--no-schema-pack' } as const;
- const resume = stored ? ` Resume it with: gbrain sync --source ${cursor.sourceId} --no-pull${SYNC_PROCESSING_KEYS.filter(key => stored[key]).map(key => ` ${flags[key]}`).join('')}`
- + ' (or omit the conflicting flag to adopt the stored options).' : '';
- const error = new OperationError('invalid_params', 'The unfinished sync has different or unknown processing options.',
- `The unfinished sync cursor for source ${cursor.sourceId} stores ${stored ? SYNC_PROCESSING_KEYS.map(key => `${key}=${stored[key]}`).join(', ') : 'no processing options'}.${resume}`
- + ' After resolving pending requests, use --retry-failed for explicit rediscovery; existing requests are not rewritten.');
- error.detail = 'cursor_processing_options_conflict';
- throw error;
- }
+ const merged: SyncProcessingOptions = !stored ? processingOptions : cursor.companyReceiptId ? stored
+ : { noEmbed: stored.noEmbed || processingOptions.noEmbed, noExtract: stored.noExtract || processingOptions.noExtract, noSchemaPack: stored.noSchemaPack || processingOptions.noSchemaPack };
+ const inherited = stored && !cursor.companyReceiptId ? SYNC_PROCESSING_KEYS.filter(option => stored[option] && !processingOptions[option]) : [];
+ if (!writerChanged && stored && digest(merged) === digest(stored)) return { cursor, inherited, writerChanged };
+ const next: Cursor = { ...cursor, authority, processingOptions: merged };
+ if (writerChanged) await withoutUnadmitted(engine, next);
+ const saved = await saveCursor(engine, key, cursor, next, false, input.assertActive, tx => validateSyncAuthority(tx, authority, '__managed_sync_checkpoint__'));
+ if (writerChanged) await faultPoint('sync:cursor_adopted', { sourceId: cursor.sourceId });
+ return { cursor: saved, inherited, writerChanged };
+}
+/** A remote caller met a cursor another principal (or the local CLI) wrote: the host's CLI resumes it. */
+function localResumeRequired(sourceId: string): OperationError {
+ return opError('sync_in_progress', `Source ${sourceId} has an unfinished sync run that another writer started.`,
+ `A remote caller resumes only its own sync runs, so nothing was synced. The brain host's CLI finishes the run with the command in fix.`,
+ { reason: 'local_resume_required', fix: { argv: ['gbrain', 'sync', '--no-pull', '--source', sourceId], consent: [], actor: 'user', requires_exclusive: false,
+ why: `Finishes the unfinished sync run of source ${sourceId} under the brain host's CLI writer.`,
+ user_message: `Source ${sourceId} has an unfinished sync that another writer started. Please run the command shown in a terminal on the brain host.`,
+ verify: { argv: ['gbrain', 'sync', 'status', '--source', sourceId, '--json'] } } });
+}
+/** The principal that admitted (or will admit) a frozen member: the authority frozen in its own intent. */
+const admittedBy = (member: Pending, cursor: Pick<Cursor, 'authority'>): Principal => member.intent.syncAuthority?.writer.principal ?? cursor.authority.writer.principal;
+/** The rows of admitted members, each read under its own admitting principal (one read per principal, normally one). */
+async function readAdmitted(engine: Pick<BrainEngine, 'executeRaw'>, cursor: Pick<Cursor, 'authority'>, members: Pending[], committedOnly = false): Promise<WriteRequest[]> {
+ const byPrincipal = new Map<string, { principal: Principal; ids: string[] }>();
+ for (const member of members) {
+ const principal = admittedBy(member, cursor), slot = principalKey(principal);
+ if (!byPrincipal.has(slot)) byPrincipal.set(slot, { principal, ids: [] });
+ byPrincipal.get(slot)!.ids.push(member.requestId);
+ }
+ const rows: WriteRequest[] = [];
+ for (const { principal, ids } of byPrincipal.values()) {
+ rows.push(...await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[])${committedOnly ? " AND state='committed'" : ''}`,
+ [principal.kind, principal.id, ids]));
}
+ return rows;
+}
+/** Cancels a window's queued members, each group of them under its own admitting principal. */
+async function cancelAdmittedWindow(engine: BrainEngine, cursor: Pick<Cursor, 'authority'>, window: Pending[][], root: string | null,
+ fence?: Omit<CursorFence, 'principal'>): Promise<boolean> {
+ const byPrincipal = new Map<string, { principal: Principal; members: Pending[] }>();
+ for (const member of window.flat()) {
+ const principal = admittedBy(member, cursor), slot = principalKey(principal);
+ if (!byPrincipal.has(slot)) byPrincipal.set(slot, { principal, members: [] });
+ byPrincipal.get(slot)!.members.push(member);
+ }
+ for (const { principal, members } of byPrincipal.values()) {
+ if (!await cancelWindow(engine, [members], principal, root, fence && { ...fence, principal })) return false;
+ }
+ return true;
+}
+/** Drops (in place) the frozen members of `next` no request was admitted for: the head and its group, or the window groups from the first unadmitted one on. */
+async function withoutUnadmitted(engine: BrainEngine, next: Cursor): Promise<void> {
+ const head = next.pending;
+ if (!head) return;
+ const window = next.window ?? [];
+ const admitted = new Set((await readAdmitted(engine, next, [head, ...window.flat()])).map(row => row.request_id));
+ if (!admitted.has(head.requestId)) { delete next.pending; delete next.group; delete next.window; return; }
+ const kept = window.findIndex(group => !group.every(member => admitted.has(member.requestId)));
+ if (kept === -1) return;
+ if (kept === 0) delete next.window; else next.window = window.slice(0, kept);
}
/** #5988: a managed dry run lists the holds the pending (or newly discovered) imports would earn, read-only. */
@@ -558,7 +623,6 @@ async function holdUnderGate(engine: BrainEngine, input: { cursor: Cursor; key:
/** #6643: the re-freeze replaces a knock-on: the new pending carries this instead of `converted`, and the run counts it. */
knockOn?: { attempts: number; root: string | null } })): Promise<Cursor | 'pending'> {
const { cursor, key, pending, assertActive } = input;
- const principal = cursor.authority.writer.principal;
const base: Cursor = input.base ?? { ...cursor }; delete base.group; delete base.window; delete base.pending;
const [failedRow] = await engine.executeRaw<{ sequence: string | number | null }>('SELECT sequence::text AS sequence FROM persistence_requests WHERE id=$1::uuid', [input.failedId]);
const after = failedRow?.sequence == null ? null : String(failedRow.sequence);
@@ -566,14 +630,14 @@ async function holdUnderGate(engine: BrainEngine, input: { cursor: Cursor; key:
const deadline = performance.now() + input.waitMs;
// #6643: the window and the run's queued suffix are cancelled only while the cursor still holds this entry, so a
// converter that lost the cursor swap to another drainer never cancels the replacement the winner admitted.
- const fence = { cursorKey: key, expectedRequestId: cursor.pending?.requestId ?? pending.requestId, principal, worktreeId: cursor.binding.worktree_id };
+ const fence = { cursorKey: key, expectedRequestId: cursor.pending?.requestId ?? pending.requestId, worktreeId: cursor.binding.worktree_id };
for (;;) {
assertActive();
- if (cursor.window?.length && !await cancelWindow(engine, cursor.window, principal, pending.requestId, fence)) return currentCursor(engine, key, cursor);
+ if (cursor.window?.length && !await cancelAdmittedWindow(engine, cursor, cursor.window, pending.requestId, fence)) return currentCursor(engine, key, cursor);
if (after !== null) {
const queued = await engine.executeRaw<WriteRequest>(`SELECT * FROM persistence_requests WHERE worktree_id=$1::uuid AND intent->>'runId'=$2 AND state='queued'
AND ${SYNC_PAGE_KINDS_SQL} AND sequence>$3::bigint ORDER BY sequence`, [cursor.binding.worktree_id, cursor.runId, after]);
- if (queued.length && !await cancelRowsUnderCursor(engine, fence, queued, knockOnDetail('suffix_cancelled', pending.requestId))) return currentCursor(engine, key, cursor);
+ if (queued.length && !await cancelRowsUnderCursor(engine, { ...fence, principal: admittedBy(pending, cursor) }, queued, knockOnDetail('suffix_cancelled', pending.requestId))) return currentCursor(engine, key, cursor);
}
const saved = await engine.transaction(async tx => {
assertActive();
@@ -624,7 +688,7 @@ async function holdUnderGate(engine: BrainEngine, input: { cursor: Cursor; key:
async function convertBlockedCursor(engine: BrainEngine, blocked: Cursor, key: string, assertActive: () => void,
run: Parameters<typeof freezeEntry>[4] & { observedAt?: string }): Promise<Cursor> {
const previous = blocked.pending!;
- const failed = await getWriteRequest(engine, blocked.authority.writer.principal, previous.requestId);
+ const failed = await getWriteRequest(engine, admittedBy(previous, blocked), previous.requestId);
if (!failed || !['failed', 'conflict', 'cancelled'].includes(failed.state)) return blocked;
// #6643: a knock-on is re-frozen by the drain itself (settleFailedRequest → recoverKnockOn), with or without a screen.
if (isSyncKnockOn(failed)) return blocked;
@@ -1036,7 +1100,7 @@ async function formGroup(engine: BrainEngine, head: Cursor, pending: Pending, ke
// ungrouped intent. The group is not formed (nothing was admitted) and the single path takes that request; any
// other intent under the head's request ID stays an idempotency_conflict.
if (!(error instanceof OperationError && error.code === 'idempotency_conflict')) throw error;
- const prior = await getWriteRequest(engine, head.authority.writer.principal, pending.requestId);
+ const prior = await getWriteRequest(engine, admittedBy(pending, head), pending.requestId);
if (prior?.digest !== intentDigest({ operation: 'submit_job', sourceId: head.sourceId, slug: pending.slug, callerIntent: pending.intent })) throw error;
return currentCursor(engine, key, head);
}
@@ -1166,10 +1230,7 @@ async function admitAhead(engine: BrainEngine, cursor: Cursor, key: string, bulk
/** Admits window group `slot` when its requests are missing; false when they are still missing (retried on the next pass, or when it becomes the cursor's group). */
async function admitWindowGroup(engine: BrainEngine, cursor: Cursor, key: string, slot: number): Promise<boolean> {
const members = cursor.window![slot]!;
- const principal = cursor.authority.writer.principal;
- const admitted = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[])',
- [principal.kind, principal.id, members.map(member => member.requestId)]);
- if ((admitted[0]?.n ?? 0) >= members.length) return true;
+ if ((await readAdmitted(engine, cursor, members)).length >= members.length) return true;
const rows = await admitGroup(engine, members, cursor, async tx => {
const [held] = await tx.executeRaw<{ request_id: string | null }>(`SELECT completed_keys->0->'window'->($3::int)->0->>'requestId' AS request_id FROM op_checkpoints WHERE op=$1 AND fingerprint=$2 FOR SHARE`, [OP, key, slot]);
return held?.request_id === members[0]!.requestId;
@@ -1186,9 +1247,7 @@ async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk:
drainStartedAt: number, onProgress: SyncOpts['onProgress'], ahead?: (cursor: Cursor) => Promise<Cursor>): Promise<{ cursor: Cursor } | { result: SyncResult }> {
const signal = wait.signal;
const members = cursor.group!;
- const principal = cursor.authority.writer.principal;
- let rows = await engine.executeRaw<WriteRequest>('SELECT * FROM persistence_requests WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[])',
- [principal.kind, principal.id, members.map(member => member.requestId)]);
+ let rows = await readAdmitted(engine, cursor, members);
if (rows.length < members.length) {
// #6075: a pass that froze the head before it was grouped may have admitted it on the single path. The group is
// dropped and the single path takes that request; the followers were never admitted (a group admits in one
@@ -1240,9 +1299,7 @@ async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk:
next.window = [...next.window];
// Window groups that lanes already committed are passed in this same save: the feeder's cost per wait stays
// one save however many groups committed meanwhile. It stops at the first group not wholly committed.
- const ids = next.window.flat().map(member => member.requestId);
- const done = new Map((await engine.executeRaw<WriteRequest>(`SELECT request_id,state,outcome FROM persistence_requests
- WHERE principal_kind=$1 AND principal_id=$2 AND request_id=ANY($3::uuid[]) AND state='committed'`, [principal.kind, principal.id, ids])).map(row => [row.request_id, row]));
+ const done = new Map((await readAdmitted(engine, cursor, next.window.flat(), true)).map(row => [row.request_id, row]));
while (next.window.length && next.window[0]!.every(member => done.has(member.requestId))) {
const group = next.window.shift()!;
for (const member of group) countCommitted(next.counts, member, done.get(member.requestId)!.outcome);
@@ -1260,7 +1317,7 @@ async function groupStep(engine: BrainEngine, cursor: Cursor, key: string, bulk:
// A failed page stops the run: groups admitted ahead of it are cancelled, never published after it.
// #6643: fenced on the cursor this pass read, and naming the stuck request as the cancelled groups' knock-on root.
if (failed && next.window) {
- if (!await cancelWindow(engine, next.window, principal, stuck!.requestId, { cursorKey: key, expectedRequestId: cursor.pending!.requestId, principal, worktreeId: cursor.binding.worktree_id })) {
+ if (!await cancelAdmittedWindow(engine, cursor, next.window, stuck!.requestId, { cursorKey: key, expectedRequestId: cursor.pending!.requestId, worktreeId: cursor.binding.worktree_id })) {
return { cursor: await currentCursor(engine, key, cursor) };
}
next.dropped = withDropped(next.dropped, next.window, stuck!.requestId);
@@ -1316,19 +1373,16 @@ async function retireCompletedCursor(engine: BrainEngine, key: string, completed
return readCursor(engine, key);
}
/** What the hold report needs from a managed run: its source, cursor and authority. */
-interface HoldRunState { sourceId?: string; incarnation?: string; remote?: boolean; cursor?: () => Cursor | CursorHeader | null }
+interface HoldRunState { sourceId?: string; incarnation?: string; remote?: boolean; cursor?: () => Cursor | CursorHeader | null;
+ /** #6712 PR 1: what the fan-in folded, and what resuming the source's one cursor kept from it. */
+ fanIn?: NonNullable<SyncResult['cursorFanIn']>; adopted?: { inherited: Array<keyof SyncProcessingOptions>; writerChanged: boolean; optionsDiffer: boolean;
+ syncOptions: SyncCursorOptions | null; processingOptions: SyncProcessingOptions | null } }
/**
* One immutable page is admitted at a time; foreground writes can never sit behind a whole scan.
* #5988: every result (resumed, no-change and blocked runs included) carries this run's holds and the source's outstanding total.
*/
-/** The durable cursor key performManagedSync would use for these options, so --retry-failed can count only the failures it retries. */
-export async function managedSyncCursorKey(engine: BrainEngine, opts: SyncOpts): Promise<string> {
- const context = await resolveManagedSyncContext(engine, opts);
- const authority = await managedSyncAuthority(engine, context.sourceId, context.incarnation, opts.repoPath ?? context.root);
- return (await selectManagedCursor(engine, { opts, context, authority, company: currentCompanyBrainSync(context.sourceId) })).key;
-}
/**
* `--retry-failed` on an unfinished cursor whose pending request failed (or whose run has a ledger row). #6340: a pending
* request that failed on a page fault (a page that moved, a dirty file) converts in place with the frozen manifest; every
@@ -1338,7 +1392,7 @@ async function retryFailedStart(engine: BrainEngine, cursor: Cursor, key: string
processingOptions: SyncProcessingOptions; syncOptions: SyncCursorOptions; startupConfig: BrainEngine; frozenRun: Parameters<typeof freezeEntry>[4]; runStartedAt: string;
discoveryRun: string; assertActive: () => void }): Promise<{ cursor: Cursor; discoveryTarget?: string } | { wait: RetryWait } | null> {
const { opts, context, authority, processingOptions, syncOptions, assertActive } = input;
- const failed = cursor.pending ? await getWriteRequest(engine, cursor.authority.writer.principal, cursor.pending.requestId) : null;
+ const failed = cursor.pending ? await getWriteRequest(engine, admittedBy(cursor.pending, cursor), cursor.pending.requestId) : null;
assertActive();
// #6643: a knock-on, and a checkpoint refused only by a receipt that no longer blocks it, recover in place in the drain
// (settleFailedRequest), which waits only on the narrowed gate; neither rediscovers the frozen manifest.
@@ -1404,13 +1458,21 @@ async function performManagedPass(engine: BrainEngine, opts: SyncOpts, slice?: {
screened: 'entries' in (cursor ?? {}) ? (cursor as Cursor).entries.slice(0, cursor!.index).filter(entry => entry.action === 'import').length : 0 });
const recovered = state.remote ? undefined : recoveredReport(state.sourceId, cursor?.counts.recovered);
const fences = fencesNormalizedReport(state.sourceId, cursor?.counts.fences, state.remote === true);
- return { ...synced, ...report, ...(!state.remote && cursor?.convertedFromFailed?.length ? { converted_from_failed: cursor.convertedFromFailed } : {}),
+ return { ...synced, ...report, ...adoptionReport(state), ...(!state.remote && cursor?.convertedFromFailed?.length ? { converted_from_failed: cursor.convertedFromFailed } : {}),
...(recovered ? { recovered_frontmatter: recovered } : {}), ...(fences ? { fences_normalized: fences } : {}) };
} catch {
return synced;
}
}
+/** #6712 PR 1: the result fields of a resumed cursor: the opt-outs it kept from the cursor, and what the fan-in folded. */
+function adoptionReport(state: HoldRunState): Pick<SyncResult, 'inherited_options' | 'cursorAdopted' | 'cursorFanIn'> {
+ const adopted = state.adopted;
+ return { ...(adopted?.inherited.length ? { inherited_options: adopted.inherited } : {}),
+ ...(adopted && (adopted.writerChanged || state.fanIn?.adopted || adopted.optionsDiffer) ? { cursorAdopted: { writer_changed: adopted.writerChanged, legacy_key: state.fanIn?.adopted === true,
+ ...(state.remote ? {} : { sync_options: adopted.syncOptions, processing_options: adopted.processingOptions }) } } : {}),
+ ...(state.fanIn ? { cursorFanIn: state.fanIn } : {}) };
+}
async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxPages: number; maxMs: number } | undefined, state: HoldRunState): Promise<SyncResult> {
await assertManagedSyncActive(engine);
if (opts.sourceId && !currentCompanyBrainSync(opts.sourceId) && await getCompanyBrainProfile(engine, opts.sourceId)) {
@@ -1422,14 +1484,12 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
if (!opts.dryRun) await assertManagedSyncAllowed(engine, context.binding.worktree_id, context.sourceId);
const authority = await managedSyncAuthority(engine, context.sourceId, context.incarnation, opts.repoPath ?? context.root);
const company = currentCompanyBrainSync(context.sourceId);
- // #6696: the one boundary that normalizes the strategy (fresh cursors only); discovery below reads the selected opts.
- const selected = await selectManagedCursor(engine, { opts, context, authority, company });
- opts = selected.opts;
const processingOptions = syncProcessingOptions(opts);
- const syncOptions = selected.syncOptions;
+ const syncOptions = syncCursorOptions(opts);
const frozenRun: Parameters<typeof freezeEntry>[4] = { syncOptions, ...(opts.repoPath ? { repoPath: resolve(opts.repoPath) } : {}), ...(opts.embedDeferred ? { embedDeferred: true } : {}) };
const runStartedAt = new Date().toISOString();
- const key = selected.key;
+ // #6712 PR 1: one cursor per incarnation (and company approval); the fan-in below may pick an older key's cursor to finish in place.
+ let key = managedCursorKey(context.incarnation, company);
let cursor: Cursor | null = null;
let missingManifestCursor: CursorHeader | null = null;
if (!company) Object.assign(state, { sourceId: context.sourceId, incarnation: context.incarnation, remote: authority.writer.remote, cursor: () => cursor });
@@ -1459,6 +1519,13 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
};
try {
assertActive();
+ const resolution = await resolveManagedCursor(engine, { sourceId: context.sourceId, incarnation: context.incarnation, company, assertActive, readOnly: !!opts.dryRun });
+ key = resolution.key;
+ if (resolution.adoptedLegacyKey || resolution.superseded.length || resolution.retained.length) state.fanIn = { adopted: !!resolution.adoptedLegacyKey, superseded: resolution.superseded.length, retained: resolution.retained.length };
+ // #6712 PR 1: a superseded run's write still in flight settles before the adopted run publishes beside it.
+ const waiting = resolution.waitFor && !opts.dryRun
+ ? (await engine.executeRaw<{ completed_keys: [CursorHeader] }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [OP, key]))[0]?.completed_keys?.[0] : undefined;
+ if (waiting) return { ...result(waiting, 'partial', 'writer_pending'), ...(authority.writer.remote ? {} : { retryWait: { ...resolution.waitFor!, retry_after_ms: 5000 } }) };
try { cursor = await readCursor(engine, key); }
catch (error) {
if (!(error instanceof MissingSyncManifest) || !opts.retryFailed || opts.dryRun || company) throw error;
@@ -1473,8 +1540,15 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
cursor = replaced;
}
assertActive();
+ if (cursor && !cursor.done && !opts.dryRun) {
+ const adopted = await adoptCursor(engine, key, cursor, { authority, processingOptions, embedDeferred: opts.embedDeferred, assertActive });
+ cursor = adopted.cursor;
+ if (adopted.inherited.length || adopted.writerChanged || resolution.adoptedLegacyKey || digest(cursor.syncOptions ?? syncOptions) !== digest(syncOptions)) state.adopted = { inherited: adopted.inherited, writerChanged: adopted.writerChanged,
+ syncOptions: cursor.syncOptions ?? null, processingOptions: cursor.processingOptions ?? null, optionsDiffer: digest(cursor.syncOptions ?? syncOptions) !== digest(syncOptions) };
+ }
+ assertActive();
if (company && opts.retryFailed && cursor && !cursor.done && !opts.dryRun) {
- const failed = cursor.pending ? await getWriteRequest(engine, cursor.authority.writer.principal, cursor.pending.requestId) : null;
+ const failed = cursor.pending ? await getWriteRequest(engine, admittedBy(cursor.pending, cursor), cursor.pending.requestId) : null;
const unfinished = await engine.executeRaw("SELECT id FROM persistence_requests WHERE source_id=$1 AND (state IN ('queued','running','recovering') OR recovery IS NOT NULL) LIMIT 1", [cursor.sourceId]);
assertActive();
// #6643: a knock-on recovers in the drain (recoverKnockOn), which keeps its per-index and per-run budgets.
@@ -1536,7 +1610,6 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
{ sourceId: cursor.sourceId, processingOptions: cursor.processingOptions, syncOptions: cursor.syncOptions ?? syncOptions, repoPath: frozenRun.repoPath },
`The unfinished sync cursor of source ${cursor.sourceId} was written under an older binding (its owner epoch, topology generation, worktree or root changed since), so this run stopped without importing; the retry rediscovers against the current binding.`);
}
- assertCursorProcessingOptions(cursor, processingOptions, opts.explicitProcessing);
if (opts.dryRun) return dryRun(cursor);
frozenRun.screen = company ? null : await loadSyncScreenRun(startupConfig, cursor.sourceId, cursor.processingOptions ?? processingOptions, authority.writer.remote);
const observedAt = frozenRun.observedAt = cursor.discoveredAt ?? runStartedAt;
@@ -1592,7 +1665,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
if (!cursor.pending) continue; // another owner-loop advanced the cursor
const pending: Pending = cursor.pending;
phase = 'admission'; stampDrainStep('admission', signal);
- const prior = await getWriteRequest(engine, cursor.authority.writer.principal, pending.requestId);
+ const prior = await getWriteRequest(engine, admittedBy(pending, cursor), pending.requestId);
assertActive();
// #5470/#5984: a frozen entry whose publication would change nothing advances the cursor without an admission.
const screened: Cursor = cursor;
@@ -1696,7 +1769,7 @@ async function runManagedSync(engine: BrainEngine, opts: SyncOpts, slice: { maxP
// waits for them), is transient admission back-pressure, not a sync failure to record. #6340: neither is a lost
// database connection or a statement timeout: the cursor and its frozen manifest stay, and the next pass resumes them.
if (!['permission_denied', 'worktree_refreshing', 'refresh_recovery_required'].includes(code) && !isWriteCapacityWait(error) && !(error instanceof LockStolenError)
- && !isRetryableConnError(error) && !isStatementTimeoutError(error) && !(code === 'invalid_params' && phase === 'resume' && (await engine.executeRaw("SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'code' IS DISTINCT FROM 'invalid_params'", [key])).length > 0)) {
+ && !isRetryableConnError(error) && !isStatementTimeoutError(error)) {
const [stored] = cursor ? [] : await engine.executeRaw<{ completed_keys: [CursorHeader] }>('SELECT completed_keys FROM op_checkpoints WHERE op=$1 AND fingerprint=$2', [OP, key]);
const failedCursor = cursor ?? stored?.completed_keys?.[0];
const { failure } = await recordManagedSyncFailure(engine, { source_id: context.sourceId, source_incarnation: context.incarnation, path: cursor?.entries[cursor.index]?.path ?? failedCursor?.pending?.intent.path ?? `<${phase}>`, code,
diff --git a/src/core/persistence/sync-wire.ts b/src/core/persistence/sync-wire.ts
index 79aace8116..25b3d3aad9 100644
--- a/src/core/persistence/sync-wire.ts
+++ b/src/core/persistence/sync-wire.ts
@@ -2,6 +2,7 @@ import { isAbsolute } from 'node:path';
import type { SyncOpts } from '../../commands/sync.ts';
import { opError } from '../ops/contract.ts';
import { SYNC_PROCESSING_KEYS } from './sync-authority.ts';
+import { WIRE_SKEW_WINDOWS } from '../wire-skew.ts';
export const SYNC_BOOLEAN_FLAGS = {
'--full':'full','--dry-run':'dryRun','--no-pull':'noPull','--no-embed':'noEmbed','--no-extract':'noExtract',
@@ -25,11 +26,12 @@ export function validateSyncWireParams(value: Record<string,unknown>): SyncWireP
else if(stringFields.has(key)) { if(typeof item!=='string'||!item||item.length>32768||item.includes('\0'))throw invalid(); }
else if(['exclude','includeHidden'].includes(key)) {
if(!Array.isArray(item)||item.length>256||item.some(v=>typeof v!=='string'||!v||v.length>4096||v.includes('\0')))throw invalid();
- } else if(key==='explicitProcessing') {
+ } else if(key===WIRE_SKEW_WINDOWS.explicitProcessing.field) {
+ // #6712 PR 1: accepted from an older client and ignored until the window in wire-skew.ts closes.
if(!Array.isArray(item)||new Set(item).size!==item.length||item.some(v=>!(SYNC_PROCESSING_KEYS as readonly unknown[]).includes(v)))throw invalid();
} else throw invalid();
}
- const options=value.options as SyncOpts;
+ const { [WIRE_SKEW_WINDOWS.explicitProcessing.field]: _ignored, ...options } = value.options as SyncOpts & Record<string, unknown>;
if(options.strategy&&!['markdown','code','auto'].includes(options.strategy))throw invalid();
return {options:{...options},cwd:value.cwd,timeoutSeconds:value.timeoutSeconds};
}
diff --git a/src/core/serve-sync-runner.ts b/src/core/serve-sync-runner.ts
index 7a63e5468e..2eb24675c3 100644
--- a/src/core/serve-sync-runner.ts
+++ b/src/core/serve-sync-runner.ts
@@ -56,7 +56,7 @@
import { isAdmissionOrigin, withAdmissionOrigin } from './persistence/admission-origin.ts';
import { randomUUID } from 'node:crypto';
-import { typedSyncProcessing, withLegacySyncDelegation } from './persistence/sync-authority.ts';
+import { withLegacySyncDelegation } from './persistence/sync-authority.ts';
import { verifyLocalWriter, withVerifiedLocalRegistration } from './persistence/identity.ts';
import { readManagedMode } from './persistence/managed-mode.ts';
import { OperationError } from './ops/contract.ts';
diff --git a/src/core/wire-skew.ts b/src/core/wire-skew.ts
new file mode 100644
index 0000000000..f9ee6bb688
--- /dev/null
+++ b/src/core/wire-skew.ts
@@ -0,0 +1,14 @@
+/**
+ * Wire-compatibility windows: fields a gbrain process still accepts from an older peer after it stopped using them.
+ *
+ * Master ships many PATCH releases a day, so a window counted in releases lasts hours. Each window is a calendar
+ * period plus a version floor: a field is accepted (validated, then ignored) until `accept_until`, and only peers below
+ * `floor` still send it. After `accept_until` the field may be deleted from the wire tables that cite its entry here.
+ */
+export interface WireSkewWindow { field: string; floor: string; accept_until: string; why: string }
+
+export const WIRE_SKEW_WINDOWS = {
+ /** #6712 PR 1: the managed cursor's processing options are inherited, so the explicit-flag list no longer decides anything. */
+ explicitProcessing: { field: 'explicitProcessing', floor: '0.60.249.0', accept_until: '2026-11-14',
+ why: 'Sync clients below the floor send the processing flags their user typed (#6317, #6696); a resume now inherits the cursor\'s opt-outs instead.' },
+} as const satisfies Record<string, WireSkewWindow>;
diff --git a/test/context/sync-ipc-validation.test.ts b/test/context/sync-ipc-validation.test.ts
index 33b2150015..6b169bde38 100644
--- a/test/context/sync-ipc-validation.test.ts
+++ b/test/context/sync-ipc-validation.test.ts
@@ -40,11 +40,12 @@ describe('validateDelegatedSyncOptions', () => {
expect(v.options).not.toBe(raw as never);
});
- test('#6317: the managed catch-up fields validate by shape (lanes 1..16, explicitProcessing from the three processing keys)', () => {
- const ok = validateDelegatedSyncOptions({ noBulk: true, lanes: 4, explicitProcessing: ['noEmbed', 'noExtract'], timeoutSeconds: 60 });
+ // #6712 PR 1: explicitProcessing is still validated by shape (an older CLI sends it) but dropped: the cursor's opt-outs are inherited.
+ test('#6317: the managed catch-up fields validate by shape (lanes 1..16, explicitProcessing from the three processing keys, accepted and ignored)', () => {
+ const ok = validateDelegatedSyncOptions({ noBulk: true, lanes: 4, explicitProcessing: ['noEmbed', 'noExtract'], timeoutSeconds: 60 } as never);
expect(ok.ok).toBe(true);
if (!ok.ok) throw new Error('unreachable');
- expect(ok.options).toEqual({ noBulk: true, lanes: 4, explicitProcessing: ['noEmbed', 'noExtract'], timeoutSeconds: 60 });
+ expect(ok.options).toEqual({ noBulk: true, lanes: 4, timeoutSeconds: 60 });
for (const lanes of [0, 17, 1.5, '4']) expect(validateDelegatedSyncOptions({ lanes, timeoutSeconds: 60 })).toEqual({ ok: false, error: 'invalid_options:lanes' });
for (const explicitProcessing of ['noEmbed', ['repoPath'], [1], ['noEmbed', 'noEmbed', 'noExtract', 'noSchemaPack']]) {
expect(validateDelegatedSyncOptions({ explicitProcessing, timeoutSeconds: 60 })).toEqual({ ok: false, error: 'invalid_options:explicitProcessing' });
diff --git a/test/e2e/persistence-request-indexes-postgres.test.ts b/test/e2e/persistence-request-indexes-postgres.test.ts
index ae356a13f3..e890c3883e 100644
--- a/test/e2e/persistence-request-indexes-postgres.test.ts
+++ b/test/e2e/persistence-request-indexes-postgres.test.ts
@@ -55,7 +55,7 @@ async function fixture() {
await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
await claimWorktree(engine, id, root);
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
- return { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true, explicitProcessing: [] } };
+ return { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true } };
}
const planNodes = (plan: Record<string, unknown>): Array<Record<string, unknown>> =>
[plan, ...((plan.Plans as Array<Record<string, unknown>> | undefined) ?? []).flatMap(planNodes)];
diff --git a/test/fix-wave-4-integration.test.ts b/test/fix-wave-4-integration.test.ts
index 760c5539b1..b0c040cd6a 100644
--- a/test/fix-wave-4-integration.test.ts
+++ b/test/fix-wave-4-integration.test.ts
@@ -92,7 +92,7 @@ test('X1: an upgrade from v178 builds the request indexes; managed working-tree
await importFromContent(engine, 'hand', legacy.toString('utf8'), { sourceId: id, noEmbed: true, sourcePath: 'hand.md' });
await claimWorktree(engine, id, root);
});
- const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true, workingTree: true, explicitProcessing: [] };
+ const opts = { sourceId: id, noPull: true, noEmbed: true, noExtract: true, workingTree: true };
for (let run = 0; run < 3; run++) {
const result = await performManagedSync(engine, opts);
await disposePersistenceConsumer(engine);
diff --git a/test/fixtures/persistence-sync-options-child.ts b/test/fixtures/persistence-sync-options-child.ts
index cc69c82c7e..c94bd246ae 100644
--- a/test/fixtures/persistence-sync-options-child.ts
+++ b/test/fixtures/persistence-sync-options-child.ts
@@ -20,13 +20,16 @@ const opts = { sourceId: input.sourceId, repoPath: input.root, noPull: true, noE
const requests = () => engine.executeRaw('SELECT id,request_id,state,intent FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [input.sourceId]);
try {
const before = await requests();
+ // #6712 PR 1: `resume` resumes with the opposite --no-embed; the cursor's opt-outs are inherited instead of refused,
+ // and the pending request keeps the options it was admitted with.
let changedOptions: unknown;
+ let result: Awaited<ReturnType<typeof performManagedSync>> | undefined;
if (process.argv[3] === 'resume') {
- try { await performManagedSync(engine, { ...opts, noEmbed: !input.noEmbed }); }
- catch (error) { changedOptions = { code: (error as { code?: string }).code }; }
+ result = await performManagedSync(engine, { ...opts, noEmbed: !input.noEmbed });
+ changedOptions = { inherited: result.inherited_options ?? [] };
}
const afterChangedOptions = await requests();
- const result = await performManagedSync(engine, { ...opts, retryFailed: true });
+ result ??= await performManagedSync(engine, { ...opts, retryFailed: true });
await disposePersistenceConsumer(engine);
const beforeDrain = await engine.executeRaw('SELECT kind,state FROM persistence_effects WHERE source_id=$1 ORDER BY kind', [input.sourceId]);
await engine.executeRaw("UPDATE persistence_effects SET next_attempt_at=now() WHERE source_id=$1 AND kind='embedding'", [input.sourceId]);
diff --git a/test/managed-sync-checkpoint-replaced.test.ts b/test/managed-sync-checkpoint-replaced.test.ts
index 3f4d81c9b6..92ea9923aa 100644
--- a/test/managed-sync-checkpoint-replaced.test.ts
+++ b/test/managed-sync-checkpoint-replaced.test.ts
@@ -71,7 +71,7 @@ async function fixture(engine: BrainEngine) {
await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
await claimWorktree(engine, id, root);
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
- return { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true, explicitProcessing: [] } };
+ return { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true } };
}
/** The sync run's admission guard (ENG-A7): the last statement of the transaction that admits the checkpoint request. */
diff --git a/test/noop-kernel-paths.test.ts b/test/noop-kernel-paths.test.ts
index b6a867490d..d5d69b9b3a 100644
--- a/test/noop-kernel-paths.test.ts
+++ b/test/noop-kernel-paths.test.ts
@@ -111,7 +111,7 @@ async function syncFixture(engine: BrainEngine) {
test('#5470 working-tree sync: a dirty file re-queued on the next run takes no second admission', async () => each(async engine => {
const f = await syncFixture(engine);
- const opts = { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, workingTree: true, explicitProcessing: [] };
+ const opts = { sourceId: f.id, noPull: true, noEmbed: true, noExtract: true, workingTree: true };
expect((await performManagedSync(engine, opts)).status).not.toBe('partial');
writeFileSync(join(f.root, 'a.md'), '---\ntitle: a\n---\nAn uncommitted working-tree edit.\n');
expect((await performManagedSync(engine, opts)).status).not.toBe('partial');
diff --git a/test/persistence-managed-sync.test.ts b/test/persistence-managed-sync.test.ts
index fa7b97a8a4..0a46bd0c71 100644
--- a/test/persistence-managed-sync.test.ts
+++ b/test/persistence-managed-sync.test.ts
@@ -15,6 +15,7 @@ import { prepareManagedSyncMutation, type SyncIntent } from '../src/core/persist
import { publishMutation } from '../src/core/persistence/coordinator.ts';
import { sha256 } from '../src/core/persistence/digest.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
+import { recordManagedSyncFailure } from '../src/core/persistence/sync-failures.ts';
import { discoverManagedSync } from '../src/core/persistence/sync-discovery.ts';
import { withCoordinatedWrite } from '../src/core/persistence/context.ts';
import { TEST_WRITE_ATTRIBUTION } from './helpers/write-attribution.ts';
@@ -632,10 +633,11 @@ test('retry-failed resets cursor when pending write is committed but failure rec
expect((await engine.getPage('a', { sourceId: f.id }))?.compiled_truth).toContain('First observation');
expect(await engine.getPage('b', { sourceId: f.id })).toBeNull();
- // A real mismatched invocation records the failure against that run.
- await expect(performManagedSync(engine, {
- sourceId: f.id, noPull: true, noEmbed: true, noExtract: true,
- })).rejects.toThrow('processing options');
+ // #6712 PR 1: a mismatched invocation no longer refuses (the cursor's processing opt-outs are inherited), so the
+ // failure an older release recorded against that run on such a refusal is written as that release wrote it.
+ await recordManagedSyncFailure(engine, { source_id: f.id, source_incarnation: cursor.incarnation, path: '', code: 'invalid_params',
+ message: 'Unfinished sync uses different processing options.', request_id: null, run_id: cursor.runId, target: null,
+ cursor_key: row.fingerprint, phase: 'resume', state: 'failed', observation_id: randomUUID() });
const failuresBefore = await engine.executeRaw(
"SELECT 1 FROM op_checkpoints WHERE op='managed-sync-failure' AND fingerprint=$1 AND completed_keys->0->>'run_id'=$2", [row.fingerprint, cursor.runId]);
expect(failuresBefore).toHaveLength(1);
diff --git a/test/persistence-sync-checkpoint-validation.test.ts b/test/persistence-sync-checkpoint-validation.test.ts
index feff486f31..69e4fe530f 100644
--- a/test/persistence-sync-checkpoint-validation.test.ts
+++ b/test/persistence-sync-checkpoint-validation.test.ts
@@ -49,7 +49,7 @@ async function fixture(engine: BrainEngine) {
await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
await claimWorktree(engine, id, root);
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
- return { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true, explicitProcessing: [] } };
+ return { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true } };
}
/** The validation statement exactly as it ran before #5762, kept only to prove parity. */
diff --git a/test/persistence-sync-cursor-options.test.ts b/test/persistence-sync-cursor-options.test.ts
index 2e28e3de97..641ef95273 100644
--- a/test/persistence-sync-cursor-options.test.ts
+++ b/test/persistence-sync-cursor-options.test.ts
@@ -19,7 +19,10 @@ import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';
// #5632: an interrupted managed sync stores its processing options on the
// cursor. Autopilot (noEmbed+noExtract defaults) and a plain CLI run (neither)
// resolve different defaults, so each refused to finish the other's cursor
-// forever. A resume that chose no processing flag now adopts the stored ones.
+// forever. #6712 PR 1 (#6552 §1) rewrote these tests: the options refusal and
+// the explicit-flag list are gone. A resume keeps the cursor's accepted
+// opt-outs (`inherited_options`), and an opt-out the caller sets applies to the
+// requests it freezes from then on; admitted requests keep their frozen options.
const home = mkdtempSync(join(tmpdir(), 'gbrain-cursor-options-'));
const engines: BrainEngine[] = [];
@@ -51,47 +54,50 @@ const isolated = (fn: (engine: BrainEngine) => Promise<void>) => withEnv({ GBRAI
const storedOptions = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ options: unknown }>(
"SELECT c.completed_keys->0->'processingOptions' AS options FROM op_checkpoints c WHERE c.op='managed-sync' AND c.completed_keys->0->>'sourceId'=$1", [id]))[0]?.options;
// What each caller passes: the autopilot job fills noEmbed/noExtract defaults; the plain CLI passes no flag.
-const autopilot = (sourceId: string): SyncOpts => ({ sourceId, noPull: true, noEmbed: true, noExtract: true, explicitProcessing: [] } as SyncOpts);
-const plainCli = (sourceId: string): SyncOpts => ({ sourceId, noPull: true, explicitProcessing: [] } as SyncOpts);
+const autopilot = (sourceId: string): SyncOpts => ({ sourceId, noPull: true, noEmbed: true, noExtract: true });
+const plainCli = (sourceId: string): SyncOpts => ({ sourceId, noPull: true });
+const importOptions = async (engine: BrainEngine, id: string) => (await engine.executeRaw<{ options: unknown }>(
+ "SELECT intent->'processingOptions' AS options FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' ORDER BY sequence", [id])).map(row => row.options);
+const none = { noEmbed: false, noExtract: false, noSchemaPack: false }, unattended = { noEmbed: true, noExtract: true, noSchemaPack: false };
-test('explicit processing flags are the ones the caller set', () => {
- const explicit = (syncAuthority as Record<string, any>).explicitSyncProcessing;
- expect(explicit({ noEmbed: true, noExtract: false })).toEqual(['noEmbed', 'noExtract']);
- expect(explicit({ noPull: true })).toEqual([]);
+test('a caller\'s processing options are the flags it set; no explicit-flag list remains', () => {
+ expect(syncAuthority.syncProcessingOptions({ noEmbed: true, noExtract: false } as SyncOpts)).toEqual({ noEmbed: true, noExtract: false, noSchemaPack: false });
+ expect((syncAuthority as Record<string, unknown>).explicitSyncProcessing).toBeUndefined();
+ expect((syncAuthority as Record<string, unknown>).typedSyncProcessing).toBeUndefined();
});
-test('a CLI-partial cursor is finished by an autopilot resume with the stored options', async () => isolated(async engine => {
+test('a CLI-partial cursor is finished by an autopilot resume; its opt-outs apply to the pages it freezes', async () => isolated(async engine => {
const id = await fixture(engine);
expect(await performManagedSync(engine, plainCli(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
- expect(await storedOptions(engine, id)).toEqual({ noEmbed: false, noExtract: false, noSchemaPack: false });
- expect((await performManagedSync(engine, autopilot(id))).status).toBe('first_sync');
+ expect(await storedOptions(engine, id)).toEqual(none);
+ const finished = await performManagedSync(engine, autopilot(id));
+ expect(finished.status).toBe('first_sync');
+ expect(finished.inherited_options).toBeUndefined();
expect(await engine.getPage('c', { sourceId: id })).not.toBeNull();
- const intents = await engine.executeRaw<{ options: unknown }>("SELECT intent->'processingOptions' AS options FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import'", [id]);
- expect(intents.map(row => row.options)).toEqual(Array(3).fill({ noEmbed: false, noExtract: false, noSchemaPack: false }));
+ expect(await importOptions(engine, id)).toEqual([none, unattended, unattended]);
+ expect(await storedOptions(engine, id)).toEqual(unattended);
}), 120_000);
-test('an autopilot-partial cursor is finished by a plain CLI resume', async () => isolated(async engine => {
+test('an autopilot-partial cursor is finished by a plain CLI resume that keeps its opt-outs', async () => isolated(async engine => {
const id = await fixture(engine);
expect(await performManagedSync(engine, autopilot(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
- expect((await performManagedSync(engine, plainCli(id))).status).toBe('first_sync');
+ const finished = await performManagedSync(engine, plainCli(id));
+ expect(finished.status).toBe('first_sync');
+ expect(finished.inherited_options).toEqual(['noEmbed', 'noExtract']);
+ expect(await importOptions(engine, id)).toEqual([unattended, unattended, unattended]);
}), 120_000);
-test('an explicit conflicting flag refuses with the stored options and the printed resume command finishes the cursor', async () => isolated(async engine => {
+// #6552 §1 probe: on the base this resume threw invalid_params (cursor_processing_options_conflict) and printed a command to retype the flags.
+test('a resume whose flags differ from the stored options finishes the cursor instead of refusing', async () => isolated(async engine => {
const id = await fixture(engine);
expect(await performManagedSync(engine, autopilot(id), { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
- const refused = await performManagedSync(engine, { sourceId: id, noPull: true, noExtract: false, explicitProcessing: ['noExtract'] } as SyncOpts)
- .then(() => null, (error: unknown) => error as { code: string; detail?: string; suggestion?: string });
- expect(refused).toMatchObject({ code: 'invalid_params', detail: 'cursor_processing_options_conflict' });
- expect(refused!.suggestion).toContain('noEmbed=true, noExtract=true, noSchemaPack=false');
- const command = `gbrain sync --source ${id} --no-pull --no-embed --no-extract`;
- expect(refused!.suggestion).toContain(command);
- const args = command.split(' ').slice(2);
- const resumed = await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: args.includes('--no-embed'), noExtract: args.includes('--no-extract'),
- explicitProcessing: ['noEmbed', 'noExtract'] } as SyncOpts);
+ const resumed = await performManagedSync(engine, { sourceId: id, noPull: true, noExtract: false, noSchemaPack: true } as SyncOpts);
expect(resumed.status).toBe('first_sync');
+ expect(resumed.inherited_options).toEqual(['noEmbed', 'noExtract']);
+ expect(await importOptions(engine, id)).toEqual([unattended, { ...unattended, noSchemaPack: true }, { ...unattended, noSchemaPack: true }]);
}), 120_000);
-test('a remote sync job keeps its frozen options while the worker adds explicit processing keys', async () => isolated(async engine => {
+test('a remote sync job finishes under its own frozen options', async () => isolated(async engine => {
const id = await fixture(engine);
const clientId = `options-client-${randomUUID()}`;
await engine.executeRaw(`INSERT INTO oauth_clients(client_id,client_name,client_secret_hash,scope,source_id,allowed_operations)
@@ -99,9 +105,7 @@ test('a remote sync job keeps its frozen options while the worker adds explicit
const ctx = { engine, remote: true, sourceId: id, auth: { clientId, principal: { kind: 'oauth_client', id: clientId }, scopes: ['admin'], sourceId: id,
allowedOperations: ['submit_job'] } } as unknown as OperationContext;
const accepted = await prepareRemoteJob(ctx, 'sync', { noPull: true });
- const explicit = (syncAuthority as Record<string, any>).explicitSyncProcessing;
- const result = await withSubmissionAuthority(accepted.authority, () => performManagedSync(engine,
- { ...accepted.data, explicitProcessing: explicit(accepted.data) } as SyncOpts));
+ const result = await withSubmissionAuthority(accepted.authority, () => performManagedSync(engine, { ...accepted.data } as SyncOpts));
expect(result.status).toBe('first_sync');
await engine.executeRaw('DELETE FROM oauth_clients WHERE client_id=$1', [clientId]);
}), 120_000);
diff --git a/test/persistence-sync-failures.serial.test.ts b/test/persistence-sync-failures.serial.test.ts
index 1f835cff3f..0c870730ca 100644
--- a/test/persistence-sync-failures.serial.test.ts
+++ b/test/persistence-sync-failures.serial.test.ts
@@ -198,7 +198,10 @@ test('full sync cannot hide an older failed incremental cursor or repeat its com
expect(await engine.executeRaw('SELECT id,state,intent,error_code FROM persistence_requests WHERE source_id=$1 ORDER BY sequence', [f.id])).toEqual(receipts);
writeFileSync(join(f.root, 'bad.md'), 'Repaired valid source observation.\n');
const fullTarget = commit(f.root);
- expect(await performManagedSync(engine, { ...options, full: true })).toMatchObject({ status: 'synced', toCommit: fullTarget });
+ // #6712 PR 1: one cursor per source, so `--full` resumes the failed cursor instead of starting its own: it stays
+ // blocked on the same failure and moves nothing (before, a full run synced under a separate key beside it).
+ expect(fullTarget).not.toBe(target);
+ expect(await performManagedSync(engine, { ...options, full: true })).toMatchObject({ status: 'blocked_by_failures', runId: blocked.runId, toCommit: target });
const [source] = await engine.executeRaw('SELECT last_commit,last_sync_at FROM sources WHERE id=$1', [f.id]);
expect(await performManagedSync(engine, options)).toEqual(blocked);
expect(await engine.executeRaw('SELECT last_commit,last_sync_at FROM sources WHERE id=$1', [f.id])).toEqual([source]);
@@ -279,7 +282,7 @@ test('managed failure retry hints name the failed cursor options locally, shell-
}
}), 120_000);
-test('--retry-failed counts only the failures of the cursor its own options select and names the others', async () => withEnv({ ...env, GBRAIN_BACKUP_CHECK: 'off', GBRAIN_SYNC_NO_EXTRACT_NUDGE: '1' }, async () => {
+test('--retry-failed counts every managed failure of the source, whatever options the failed run used (#6712 PR 1: one cursor key)', async () => withEnv({ ...env, GBRAIN_BACKUP_CHECK: 'off', GBRAIN_SYNC_NO_EXTRACT_NUDGE: '1' }, async () => {
for (const engine of engines) {
const f = await fixture(engine, { 'bad.md': '---\ntitle: [broken\n---\nRetry count fixture.\n' });
await engine.executeRaw("UPDATE sources SET config=jsonb_set(config,'{syncEnabled}','false'::jsonb) WHERE id<>$1", [f.id]);
@@ -288,12 +291,8 @@ test('--retry-failed counts only the failures of the cursor its own options sele
expect(await readManagedSyncFailures(engine, [f.id])).toHaveLength(1);
const other = await captureCli(() => runSync(engine, [...flags, '--retry-failed']));
- expect(other).toContain('1 previously-failed file(s) of this source belong to a run with different sync options and are not retried by this invocation.');
- expect(other).toContain(`gbrain sync --source ${f.id} --no-pull --retry-failed --no-embed --no-extract --no-schema-pack --exclude 'it'\\''s a dir/**'`);
- expect(other).not.toContain('Retrying 1 previously-failed file(s)');
-
- const same = await captureCli(() => runSync(engine, [...flags, '--exclude', QUOTED_EXCLUDE, '--retry-failed']));
- expect(same).toContain('Retrying 1 previously-failed file(s)...');
+ expect(other).toContain('Retrying 1 previously-failed file(s)...');
+ expect(other).not.toContain('belong to a run with different sync options');
}
}), 120_000);
diff --git a/test/persistence-sync-holds.test.ts b/test/persistence-sync-holds.test.ts
index 48219d5918..705fc6b1cc 100644
--- a/test/persistence-sync-holds.test.ts
+++ b/test/persistence-sync-holds.test.ts
@@ -291,7 +291,7 @@ test('a flagless sync converts a --no-embed cursor with its stored options, and
await engine.unsetConfig('sync.holds');
s.write('notes/broken.md', note('Fixed in the working tree only'));
// Pinned bytes still refuse, so the entry is held; the stored --no-embed survives the flagless run.
- const converted = await performManagedSync(engine, { sourceId: s.id, noPull: true, explicitProcessing: [] });
+ const converted = await performManagedSync(engine, { sourceId: s.id, noPull: true });
expect(converted.held_count).toBe(1);
const [cursor] = await engine.executeRaw<{ completed_keys: Array<{ processingOptions: { noEmbed: boolean } }> }>(
"SELECT completed_keys FROM op_checkpoints WHERE op='managed-sync' AND completed_keys->0->>'sourceId'=$1", [s.id]);
diff --git a/test/persistence-sync-legacy-files-5751.test.ts b/test/persistence-sync-legacy-files-5751.test.ts
index 22f99fb34e..f7a4a299f1 100644
--- a/test/persistence-sync-legacy-files-5751.test.ts
+++ b/test/persistence-sync-legacy-files-5751.test.ts
@@ -65,7 +65,7 @@ async function legacyFixture(engine: BrainEngine) {
await engine.executeRaw('UPDATE pages SET contextual_retrieval_mode=NULL WHERE source_id=$1', [id]);
await claimWorktree(engine, id, root);
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
- return { id, root, working: { sourceId: id, noPull: true, noEmbed: true, noExtract: true, workingTree: true, explicitProcessing: [] } };
+ return { id, root, working: { sourceId: id, noPull: true, noEmbed: true, noExtract: true, workingTree: true } };
}
const admitted = async (engine: BrainEngine, id: string) =>
(await engine.executeRaw<{ slug: string }>("SELECT slug FROM persistence_requests WHERE source_id=$1 AND intent->>'kind'='managed_sync_import' ORDER BY sequence", [id])).map(r => r.slug);
diff --git a/test/persistence-sync-options.serial.test.ts b/test/persistence-sync-options.serial.test.ts
index 0c6f9c09d4..dd004ec096 100644
--- a/test/persistence-sync-options.serial.test.ts
+++ b/test/persistence-sync-options.serial.test.ts
@@ -132,28 +132,27 @@ check('noSchemaPack bypasses the configured pack and noExtract queues no optiona
});
});
+// #6712 PR 1: a changed-option resume no longer refuses `invalid_params`; it inherits the cursor's opt-outs (reported in
+// `inherited_options`) and still never rewrites accepted work.
check('interrupted options survive resume and changed-option retries cannot rewrite accepted work', async engine => {
const f = await fixture(engine, 2);
const first = await performManagedSync(engine, f.opts, { maxPages: 1, maxMs: 1000 });
expect(first).toMatchObject({ status: 'partial', filesImported: 1 });
- const before = await cursor(engine, f.id);
const requests = await engine.executeRaw('SELECT id,intent FROM persistence_requests WHERE source_id=$1', [f.id]);
- for (const key of ['noEmbed', 'noSchemaPack', 'noExtract'] as const) {
- await expect(performManagedSync(engine, { ...f.opts, [key]: false })).rejects.toMatchObject({ code: 'invalid_params' });
- expect(await cursor(engine, f.id)).toEqual(before);
- expect(await engine.executeRaw('SELECT id,intent FROM persistence_requests WHERE source_id=$1', [f.id])).toEqual(requests);
- }
- expect(await performManagedSync(engine, f.opts)).toMatchObject({ status: 'first_sync', runId: first.runId, filesImported: 2 });
+ const resumed = await performManagedSync(engine, { ...f.opts, noEmbed: false, noSchemaPack: false, noExtract: false });
+ expect(resumed).toMatchObject({ status: 'first_sync', runId: first.runId, filesImported: 2 });
+ expect([...(resumed.inherited_options ?? [])].sort()).toEqual(['noEmbed', 'noExtract', 'noSchemaPack']);
+ expect(await engine.executeRaw('SELECT id,intent FROM persistence_requests WHERE id=ANY($1::uuid[])', [requests.map(row => (row as { id: string }).id)])).toEqual(requests);
expect((await cursor(engine, f.id)).value.processingOptions).toEqual({ noEmbed: true, noSchemaPack: true, noExtract: true });
expect(await engine.executeRaw("SELECT kind FROM persistence_effects WHERE source_id=$1 AND kind IN ('embedding','facts-backstop')", [f.id])).toEqual([]);
const retry = await fixture(engine, 2);
const interrupted = await performManagedSync(engine, retry.opts, { maxPages: 1, maxMs: 1000 });
const original = await engine.executeRaw('SELECT id,intent FROM persistence_requests WHERE source_id=$1 ORDER BY id', [retry.id]);
- await expect(performManagedSync(engine, { ...retry.opts, noSchemaPack: false })).rejects.toMatchObject({ code: 'invalid_params' });
+ // Without a failure (the refusal used to record one) `--retry-failed` has nothing to rediscover: it resumes the
+ // interrupted run with the cursor's opt-outs.
const rediscovered = await performManagedSync(engine, { ...retry.opts, noSchemaPack: false, retryFailed: true });
- expect(rediscovered.status).toBe('first_sync');
- expect(rediscovered.runId).not.toBe(interrupted.runId);
- expect((await cursor(engine, retry.id)).value.processingOptions.noSchemaPack).toBe(false);
+ expect(rediscovered).toMatchObject({ status: 'first_sync', runId: interrupted.runId, inherited_options: ['noSchemaPack'] });
+ expect((await cursor(engine, retry.id)).value.processingOptions.noSchemaPack).toBe(true);
expect(await engine.executeRaw('SELECT id,intent FROM persistence_requests WHERE id=ANY($1::uuid[]) ORDER BY id', [original.map(row => row.id)])).toEqual(original);
});
@@ -304,8 +303,8 @@ test('fresh processes resume persisted pending opt-outs under the original reque
const resumed = await child('resume');
expect(resumed.pid).not.toBe(process.pid);
expect(resumed.before).toEqual(frozen!);
- expect(resumed.changedOptions).toEqual({ code: 'invalid_params' });
- expect(resumed.afterChangedOptions).toEqual(frozen!);
+ expect(resumed.changedOptions).toEqual({ inherited: noEmbed ? ['noEmbed'] : [] });
+ expect(resumed.afterChangedOptions).toEqual(resumed.after);
expect(resumed.result).toMatchObject({ status: 'first_sync', runId: pending!.runId, added: 1, filesImported: 1 });
expect(resumed.after).toHaveLength(2);
expect(resumed.after[0]).toEqual({ ...frozen![0], state: 'committed' });
diff --git a/test/serve-sync-handoff.serial.test.ts b/test/serve-sync-handoff.serial.test.ts
index e3b149579a..c0ed9e7e69 100644
--- a/test/serve-sync-handoff.serial.test.ts
+++ b/test/serve-sync-handoff.serial.test.ts
@@ -207,7 +207,7 @@ describe('sync_start authorization hand-off (serve half)', () => {
test('a verified cli registration runs the managed drain inside the serve; sync_status carries its lines, the DrainReport and next', async () => withEnv({ GBRAIN_HOME: home }, async () => {
const f = await fixture(4);
const local = await registerLocalWriter(engine, 'cli');
- const start = await startDelegatedSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, explicitProcessing: ['noEmbed'], timeoutSeconds: 120 }, randomUUID(),
+ const start = await startDelegatedSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, timeoutSeconds: 120 }, randomUUID(),
{ registration: { id: local.id, credential: local.credential, lane: 'cli' } });
expect(start.ok).toBe(true);
const done = await waitTerminal(start.jobId!);
@@ -230,7 +230,7 @@ describe('sync_start authorization hand-off (serve half)', () => {
});
describe('maybeDelegateManagedSyncToServe (the Postgres ladder, client half)', () => {
- const baseOpts = (sourceId: string): SyncOpts => ({ sourceId, noPull: true, noEmbed: true, explicitProcessing: ['noEmbed'], drain: true });
+ const baseOpts = (sourceId: string): SyncOpts => ({ sourceId, noPull: true, noEmbed: true, drain: true });
test('--no-delegate and GBRAIN_SYNC_NO_DELEGATE=1 bypass the ladder before anything is probed', async () => withEnv({ GBRAIN_HOME: home }, async () => {
const f = await fixture(1);
@@ -381,7 +381,7 @@ describe('maybeDelegateManagedSyncToServe (the Postgres ladder, client half)', (
const f = await fixture(5);
const sock = await serveSocket();
captureStderr();
- const outcome = await maybeDelegateManagedSyncToServe(engine, ['--source', f.id, '--no-pull', '--json'], { ...baseOpts(f.id), noEmbed: undefined, explicitProcessing: [] }, deps({ sock }));
+ const outcome = await maybeDelegateManagedSyncToServe(engine, ['--source', f.id, '--no-pull', '--json'], { ...baseOpts(f.id), noEmbed: undefined }, deps({ sock }));
releaseStderr();
expect(outcome.kind).toBe('delegated');
if (outcome.kind !== 'delegated') throw new Error('unreachable');
@@ -403,7 +403,7 @@ describe('maybeDelegateManagedSyncToServe (the Postgres ladder, client half)', (
const flags = { noPull: false, dryRun: false };
captureStderr();
await implyManagedNoPull(engine, flags, f.id);
- const outcome = await maybeDelegateManagedSyncToServe(engine, ['--source', f.id, '--json'], { ...baseOpts(f.id), noPull: flags.noPull, noEmbed: undefined, explicitProcessing: [] }, deps({ sock }));
+ const outcome = await maybeDelegateManagedSyncToServe(engine, ['--source', f.id, '--json'], { ...baseOpts(f.id), noPull: flags.noPull, noEmbed: undefined }, deps({ sock }));
releaseStderr();
expect(captured.some(l => l.includes('--no-pull is implied') && l.includes(`gbrain sources refresh ${f.id}`))).toBe(true);
expect(outcome.kind).toBe('delegated');
diff --git a/test/sync-cancelled-knock-on.test.ts b/test/sync-cancelled-knock-on.test.ts
index 7a49cc4ee4..1153a0045e 100644
--- a/test/sync-cancelled-knock-on.test.ts
+++ b/test/sync-cancelled-knock-on.test.ts
@@ -76,11 +76,16 @@ test('sync status turns a cancelled knock-on into the retry sync prints, not a h
expect([...status.next!.argv!].sort()).toEqual([...printed].sort());
}), 120_000);
-test('a resume refused for conflicting cursor options leaves the recorded failure untouched', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
+// #6712 PR 1: a resume with other processing flags is no longer refused; it inherits the cursor's opt-outs and meets
+// the same failure, which it must not re-record or replace.
+test('a resume with other processing flags inherits the cursor options and leaves the recorded failure untouched', async () => withEnv({ GBRAIN_HOME: home, GBRAIN_SYNC_FAILURES_DIR: home }, async () => {
const f = await blockedRun();
const [before] = await readManagedSyncFailures(engine, [f.id]);
expect(before!.code).toBe('source_changed');
- await expect(performManagedSync(engine, { ...f.opts, noEmbed: false, explicitProcessing: ['noEmbed'] })).rejects.toMatchObject({ code: 'invalid_params' });
+ // Holds stay off as in the blocked run, so the page fault is still a failure rather than converted to a hold.
+ await engine.setConfig('sync.holds', 'fail');
+ try { expect(await performManagedSync(engine, { ...f.opts, noEmbed: false })).toMatchObject({ status: 'blocked_by_failures' }); }
+ finally { await engine.executeRaw("DELETE FROM config WHERE key='sync.holds'"); }
const [after] = await readManagedSyncFailures(engine, [f.id]);
expect(after).toMatchObject({ code: 'source_changed', observation_id: before!.observation_id, attempts: before!.attempts });
}), 120_000);
diff --git a/test/sync-delegate-ladder.test.ts b/test/sync-delegate-ladder.test.ts
index d9cd6263fe..15ae60ec18 100644
--- a/test/sync-delegate-ladder.test.ts
+++ b/test/sync-delegate-ladder.test.ts
@@ -66,8 +66,9 @@ function captureConsoleError(): { lines: string[]; restore: () => void } {
}
describe('parseDelegatedSyncArgs (default-deny)', () => {
- test('bare sync → no options but an empty explicit-processing list (#6696: a flagless run adopts the cursor), no explicit source', () => {
- expect(parseDelegatedSyncArgs([])).toEqual({ ok: true, options: { explicitProcessing: [] }, explicitSource: null });
+ // #6712 PR 1: no explicit-processing list crosses the wire any more; a resume inherits the cursor's opt-outs on either side.
+ test('bare sync → no options, no explicit source', () => {
+ expect(parseDelegatedSyncArgs([])).toEqual({ ok: true, options: {}, explicitSource: null });
});
test('the full wire-forwardable set maps field-for-field', () => {
@@ -81,8 +82,6 @@ describe('parseDelegatedSyncArgs (default-deny)', () => {
expect(r.options).toEqual({
full: true, dryRun: true, noPull: true, noEmbed: true, noExtract: true,
noSchemaPack: true, skipFailed: true, retryFailed: true, includeGitignored: true,
- // #6317: the processing flags the caller set, so the managed cursor supplies only the rest (#5632).
- explicitProcessing: ['noEmbed', 'noExtract', 'noSchemaPack'],
});
expect(r.explicitSource).toBe('notes');
});
@@ -104,8 +103,8 @@ describe('parseDelegatedSyncArgs (default-deny)', () => {
test('#6317: the managed catch-up flags are admitted explicitly (--json is rendered by this client, never forwarded)', () => {
const r = parseDelegatedSyncArgs(['--source', 'notes', '--no-pull', '--json', '--no-bulk', '--lanes', '4', '--no-embed']);
- expect(r).toEqual({ ok: true, explicitSource: 'notes', options: { noPull: true, noBulk: true, lanes: 4, noEmbed: true, explicitProcessing: ['noEmbed'] } });
- expect(parseDelegatedSyncArgs(['--no-lanes'])).toEqual({ ok: true, explicitSource: null, options: { lanes: 1, explicitProcessing: [] } });
+ expect(r).toEqual({ ok: true, explicitSource: 'notes', options: { noPull: true, noBulk: true, lanes: 4, noEmbed: true } });
+ expect(parseDelegatedSyncArgs(['--no-lanes'])).toEqual({ ok: true, explicitSource: null, options: { lanes: 1 } });
expect(parseDelegatedSyncArgs(['--lanes', '0'])).toEqual({ ok: false, refused: '--lanes (invalid value)' });
expect(parseDelegatedSyncArgs(['--lanes', '17'])).toEqual({ ok: false, refused: '--lanes (invalid value)' });
expect(parseDelegatedSyncArgs(['--lanes', 'four'])).toEqual({ ok: false, refused: '--lanes (invalid value)' });
diff --git a/test/sync-delegated-options-6696.serial.test.ts b/test/sync-delegated-options-6696.serial.test.ts
index b09a0308a1..aa8cbf0eba 100644
--- a/test/sync-delegated-options-6696.serial.test.ts
+++ b/test/sync-delegated-options-6696.serial.test.ts
@@ -4,21 +4,20 @@
*
* What these tests protect:
* - a flagless delegated run adopts an unfinished cursor's stored options,
- * exactly as the in-process CLI does: both client builders send
- * `explicitProcessing: []` instead of dropping the empty list (which made
- * every processing key explicit on the serve and refused the resume with
- * `invalid_params`);
- * - an older CLI omits the list but still sends `true` for each processing
- * flag its user typed: a newer serve reads those true-valued keys as the
- * explicit ones (a flagless payload is "no flags"), so `--no-embed` from an
- * older CLI never resumes a cursor storing `noEmbed=false` into embedding;
+ * exactly as the in-process CLI does (#6712 PR 1: neither side sends nor
+ * reads an explicit-processing list any more; a resume inherits the
+ * cursor's opt-outs);
+ * - an older CLI's typed `--no-embed` never resumes a cursor storing
+ * `noEmbed=false` into embedding: the opt-out applies to the requests the
+ * run freezes (it used to refuse the resume with `invalid_params`);
* - a runtime embedding deferral (the cost gate's auto-defer) is not a
* processing option: adopting a cursor that stores `noEmbed=false` never
- * turns embedding back on for the run, in-process or delegated. A provider
- * spy sees zero embedding calls and no embedding effect is queued.
+ * turns embedding back on for the run, in-process or delegated, and the
+ * cursor does not keep the deferral. A provider spy sees zero embedding
+ * calls and no embedding effect is queued.
*
- * Regression each guards: dropping `explicitProcessing` on either builder, the
- * serve passing `undefined` through, and the deferral riding only as `noEmbed`.
+ * Regression each guards: a list reappearing on either builder, and the
+ * deferral riding only as `noEmbed`.
* Existing coverage (`serve-sync-handoff.serial.test.ts`) delegates only onto
* fresh sources, so a resume never crossed the wire there.
*
@@ -74,7 +73,7 @@ async function fixture(count: number): Promise<{ id: string; root: string }> {
/** An unfinished cursor: one page of `count` committed under the given options, the rest still to freeze. */
async function partialCursor(id: string, opts: Partial<SyncOpts>): Promise<void> {
- expect(await performManagedSync(engine, { sourceId: id, noPull: true, explicitProcessing: [], ...opts } as SyncOpts, { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
+ expect(await performManagedSync(engine, { sourceId: id, noPull: true, ...opts } as SyncOpts, { maxPages: 1, maxMs: 1000 })).toMatchObject({ status: 'partial' });
await drainEffects();
embedded.length = 0;
}
@@ -154,12 +153,13 @@ afterAll(async () => {
rmSync(home, { recursive: true, force: true });
});
-describe('the client builders send an empty explicit-processing list', () => {
- test('parseDelegatedSyncArgs: a flagless argv sets none explicitly; a processing flag sets exactly that key', () => {
+describe('the client builders send no explicit-processing list (#6712 PR 1)', () => {
+ test('parseDelegatedSyncArgs: a flagless argv sends no list; a processing flag sends exactly its option', () => {
const flagless = parseDelegatedSyncArgs(['--source', 'acme-example', '--no-pull']);
- expect(flagless.ok && flagless.options.explicitProcessing).toEqual([]);
+ // #6712 PR 1: no list crosses the wire; the serve's resume inherits the cursor's opt-outs, as in-process.
+ expect(flagless.ok && 'explicitProcessing' in flagless.options).toBe(false);
const flagged = parseDelegatedSyncArgs(['--source', 'acme-example', '--no-pull', '--no-extract']);
- expect(flagged.ok && flagged.options.explicitProcessing).toEqual(['noExtract']);
+ expect(flagged.ok && flagged.options).toEqual({ noPull: true, noExtract: true });
});
test('a flagless delegated run adopts the unfinished cursor\'s stored options (noEmbed=true) instead of refusing', async () => withEnv(env, async () => {
@@ -168,7 +168,7 @@ describe('the client builders send an empty explicit-processing list', () => {
expect(await storedOptions(f.id)).toEqual({ noEmbed: true, noExtract: true, noSchemaPack: false });
const sock = await serveSocket();
const delegated = await quiet(() => maybeDelegateManagedSyncToServe(engine, ['--source', f.id, '--no-pull'],
- { sourceId: f.id, noPull: true, explicitProcessing: [], drain: true } as SyncOpts, deps(sock)).catch((error: unknown) => error));
+ { sourceId: f.id, noPull: true, drain: true } as SyncOpts, deps(sock)).catch((error: unknown) => error));
expect(delegated).toMatchObject({ kind: 'delegated', result: { status: 'first_sync' } });
expect(await engine.getPage('notes/n2', { sourceId: f.id })).not.toBeNull();
// The adopted options are the cursor's: no page request of this source embeds.
@@ -189,6 +189,7 @@ describe('the serve infers a missing list from an older CLI\'s true-valued flags
expect(done).toMatchObject({ state: 'done', result: { status: 'first_sync' } });
}), 180_000);
+ // #6712 PR 1 (#6552 §1): the refusal is gone. The typed opt-out applies to the requests this run freezes, so it still embeds nothing.
test('an older CLI\'s --no-embed (noEmbed: true, no list) never resumes a noEmbed=false cursor into embedding', async () => withEnv(env, async () => {
const f = await fixture(3);
await partialCursor(f.id, {});
@@ -198,9 +199,10 @@ describe('the serve infers a missing list from an older CLI\'s true-valued flags
const start = await startDelegatedSync(engine, { sourceId: f.id, noPull: true, noEmbed: true, timeoutSeconds: 120 }, randomUUID(),
{ registration: { id: local.id, credential: local.credential, lane: 'cli' } });
expect(start.ok).toBe(true);
- // The typed flag is explicit, as in-process: it conflicts with the stored noEmbed=false and the resume is refused.
const done = await quiet(() => waitTerminal(start.jobId!));
- expect(done).toMatchObject({ state: 'error', jobErrorEnvelope: { code: 'invalid_params' } });
+ expect(done.jobErrorEnvelope).toBeUndefined();
+ expect(done).toMatchObject({ state: 'done', result: { status: 'first_sync' } });
+ expect(await storedOptions(f.id)).toEqual({ noEmbed: true, noExtract: false, noSchemaPack: false });
await drainEffects();
expect(await embeddingEffects(f.id)).toBe(before);
expect(embedded).toEqual([]);
@@ -215,7 +217,7 @@ describe('a runtime embedding deferral is never lifted by cursor adoption', () =
const before = await embeddingEffects(f.id);
const sock = await serveSocket();
const delegated = await quiet(() => maybeDelegateManagedSyncToServe(engine, ['--source', f.id, '--no-pull'],
- { sourceId: f.id, noPull: true, noEmbed: true, embedDeferred: true, explicitProcessing: [], drain: true } as SyncOpts, deps(sock)).catch((error: unknown) => error));
+ { sourceId: f.id, noPull: true, noEmbed: true, embedDeferred: true, drain: true } as SyncOpts, deps(sock)).catch((error: unknown) => error));
expect(delegated).toMatchObject({ kind: 'delegated', result: { status: 'first_sync' } });
await drainEffects();
expect(await embeddingEffects(f.id)).toBe(before);
diff --git a/test/sync-legacy-retry-actions-6696.test.ts b/test/sync-legacy-retry-actions-6696.test.ts
index 811ab4fddf..33c192da9b 100644
--- a/test/sync-legacy-retry-actions-6696.test.ts
+++ b/test/sync-legacy-retry-actions-6696.test.ts
@@ -1,21 +1,15 @@
/**
- * #6696 C3: `--retry-failed` on a managed source names failures recorded under another cursor key. A failure whose run
- * predates recorded sync options used to get "gbrain sync ... with the same options as the failed run (this receipt no
- * longer records them)": a command nobody can run. Now each such row is classified, and the action printed for it
- * settles it when run:
+ * #6696 C3, revised by #6712 PR 1: `--retry-failed` on a managed source settles failures an older gbrain recorded under
+ * other cursor keys. The per-row action classifier (`managed-retry-actions.ts`) is gone: a source has one cursor key, and
+ * the current key folds older-key cursors in (the newest unfinished one finishes in place under its key, the rest are
+ * superseded with their failure rows). A failure no cursor holds at all is named with the orphan repair that retires it.
*
- * - resumable: an option set reproduces the row's cursor key exactly (the run's own options with and without the
- * source's configured strategy and --full, or the options another cursor of the source recorded); the command is
- * labelled a replay when an unfinished run holds the key, a fresh discovery when none does;
- * - safely orphaned: the existing orphan repair names the row (no cursor, an unadoptable principal, superseded);
- * - unresolved: nothing selects it now; the action finishes a current run, after which the orphan repair retires it.
+ * Fixture: one source configured with strategy `markdown`, two unfinished cursors an older gbrain left under its own keys
+ * (a `--full` run, and a newer run with an `--exclude`), both recorded before cursors kept their options, and one failure
+ * row with no cursor, for a file sync does not index (so no successful run settles it on its own).
*
- * Fixture: one source configured with strategy `markdown`, two unfinished legacy cursors (a `--full` run, and a run with
- * an `--exclude` no current option reproduces) and one failure row with no cursor at all, for a file sync does not index
- * (so no successful run settles it on its own).
- *
- * Regression that fails it: the "no longer records them" text, an unlabelled command, or an action that leaves the
- * original failure recorded.
+ * Regression that fails it: the "no longer records them" text, a legacy failure that survives the retry, or a cursor-less
+ * row with no printed way out.
*/
import { afterAll, beforeAll, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
@@ -32,6 +26,7 @@ import { claimWorktree } from '../src/core/persistence/ownership.ts';
import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';
import { performManagedSync } from '../src/core/persistence/sync-run.ts';
import { readManagedSyncFailures, recordManagedSyncFailure } from '../src/core/persistence/sync-failures.ts';
+import { __setManagedCursorKeyForTests } from '../src/core/persistence/sync-cursor-key.ts';
import { managedSyncOrphansRepair } from '../src/core/repair/managed-sync-orphans.ts';
import { runRepair } from '../src/core/repair/core.ts';
import { repairSpec } from '../src/core/repair/registry.ts';
@@ -107,7 +102,7 @@ async function fixture(engine: BrainEngine) {
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
const [{ incarnation }] = await engine.executeRaw<{ incarnation: string }>('SELECT incarnation::text AS incarnation FROM sources WHERE id=$1', [id]);
const run = (opts: Partial<SyncOpts>, budget = { maxPages: 1, maxMs: 1000 }) =>
- performManagedSync(engine, { sourceId: id, noPull: true, explicitProcessing: [], ...opts } as SyncOpts, budget);
+ performManagedSync(engine, { sourceId: id, noPull: true, ...opts } as SyncOpts, budget);
/** A failure recorded before failures kept their run's options. */
const failure = (cursor_key: string, path: string) => recordManagedSyncFailure(engine, { source_id: id, source_incarnation: incarnation, path, code: 'source_changed',
message: 'file and database disagree', request_id: null, run_id: `run-${cursor_key.slice(0, 8)}`, target: head, cursor_key, phase: 'receipt', state: 'failed',
@@ -120,13 +115,20 @@ const actionLine = (out: string, label: RegExp) => {
return found!.slice(found!.lastIndexOf(': ') + 2).trim();
};
-test('legacy failures under other keys are classified resumable / safely orphaned / unresolved, and each printed action settles its row', async () => withEnv(env, async () => { for (const engine of engines) {
+/** Runs `fn` as an older gbrain whose cursor key for this source is `key`, with the other older cursor out of its sight. */
+async function legacy<T>(engine: BrainEngine, key: string, fn: () => Promise<T>, hide?: string): Promise<T> {
+ const park = (fingerprint: string, op: string) => engine.executeRaw("UPDATE op_checkpoints SET op=$2 WHERE fingerprint=$1 AND op IN ('managed-sync','managed-sync-parked')", [fingerprint, op]);
+ __setManagedCursorKeyForTests(() => key);
+ if (hide) await park(hide, 'managed-sync-parked');
+ try { return await fn(); } finally { __setManagedCursorKeyForTests(null); if (hide) await park(hide, 'managed-sync'); }
+}
+const orphanCommand = (id: string) => `gbrain repair managed-sync-orphans --source ${id}`;
+
+test('legacy failures under older keys: one --retry-failed folds their cursors in and settles them; the printed repair settles the cursor-less row', async () => withEnv(env, async () => { for (const engine of engines) {
const { id, run, failure } = await fixture(engine);
- // Two unfinished runs recorded before cursors kept their options: a --full run and a run with an --exclude.
- expect(await run({ full: true })).toMatchObject({ status: 'partial' });
- const fullKey = (await cursorKeys(engine, id)).find(row => row.syncOptions?.full === true)!.key;
- expect(await run({ exclude: ['archive/**'] })).toMatchObject({ status: 'partial' });
- const excludeKey = (await cursorKeys(engine, id)).find(row => (row.syncOptions?.exclude as string[] | undefined)?.length)!.key;
+ const fullKey = `${id}-full`, excludeKey = `${id}-exclude`;
+ expect(await legacy(engine, fullKey, () => run({ full: true }))).toMatchObject({ status: 'partial' });
+ expect(await legacy(engine, excludeKey, () => run({ exclude: ['archive/**'] }), fullKey)).toMatchObject({ status: 'partial' });
await stripOptions(engine, fullKey); await stripOptions(engine, excludeKey);
const noCursorKey = `legacy-${randomUUID()}`;
await failure(fullKey, 'notes/n1.md'); await failure(excludeKey, 'notes/n2.md'); await failure(noCursorKey, 'assets/data.bin');
@@ -134,38 +136,29 @@ test('legacy failures under other keys are classified resumable / safely orphane
const out = await capture(() => runSyncInner(engine, ['--source', id, '--no-pull', '--retry-failed']));
expect(out).not.toContain('this receipt no longer records them');
- const line = (label: RegExp) => actionLine(out, label);
- const replay = line(/^\s+1 resumable \(replay/);
- expect(replay).toBe(`gbrain sync --source ${id} --no-pull --retry-failed --full --strategy markdown`);
- const orphaned = line(/^\s+1 safely orphaned/);
- expect(orphaned).toBe(`gbrain repair managed-sync-orphans --source ${id}`);
- const unresolved = line(/^\s+1 unresolved/);
- expect(unresolved).toBe(`gbrain sync --source ${id} --no-pull`);
- expect(await failureKeys(engine, id)).toEqual([excludeKey, fullKey, noCursorKey].sort());
+ expect(out).toContain('Retrying 3 previously-failed file(s)...');
+ expect(out).toContain(`1 of them belong to no sync run any more`);
+ expect(out).toContain(orphanCommand(id));
+ // The newer older-key cursor finished in place under its own key; the --full one was superseded with its failure.
+ expect((await cursorKeys(engine, id)).map(row => row.key)).toEqual([excludeKey]);
+ expect(await failureKeys(engine, id)).toEqual([noCursorKey]);
- // Each printed action, run as printed, settles its rows: the replay its own; the unresolved run's completion makes
- // the option-less cursor superseded, so the orphan repair then retires it along with the cursor-less row.
- await runAction(engine, replay);
- expect(await failureKeys(engine, id)).toEqual([excludeKey, noCursorKey].sort());
- await runAction(engine, unresolved);
- await runAction(engine, orphaned);
+ await runAction(engine, orphanCommand(id));
expect(await failureKeys(engine, id)).toEqual([]);
expect(await readManagedSyncFailures(engine, [id])).toEqual([]);
} }), 240_000);
-test('a cursor-less legacy failure whose key the options reproduce gets a fresh discovery (not a replay) that clears it', async () => withEnv(env, async () => { for (const engine of engines) {
+test('a cursor-less legacy failure for a file no run imports is named with the orphan repair, which clears it', async () => withEnv(env, async () => { for (const engine of engines) {
const { id, run, failure } = await fixture(engine);
// A --full run that finished and was retired: its failure row outlived its cursor and never recorded the options.
- expect(await run({ full: true }, { maxPages: 1000, maxMs: 60_000 })).toMatchObject({ status: 'first_sync' });
- const fullKey = (await cursorKeys(engine, id)).find(row => row.syncOptions?.full === true)!.key;
+ const fullKey = `${id}-full`;
+ expect(await legacy(engine, fullKey, () => run({ full: true }, { maxPages: 1000, maxMs: 60_000 }))).toMatchObject({ status: 'first_sync' });
await engine.executeRaw("DELETE FROM op_checkpoints WHERE op='managed-sync' AND fingerprint=$1", [fullKey]);
await failure(fullKey, 'assets/data.bin');
const out = await capture(() => runSyncInner(engine, ['--source', id, '--no-pull', '--retry-failed']));
expect(out).not.toContain('this receipt no longer records them');
- expect(out).not.toMatch(/resumable \(replay/);
- const fresh = actionLine(out, /^\s+1 resumable \(fresh discovery, not a replay/);
- expect(fresh).toBe(`gbrain sync --source ${id} --no-pull --retry-failed --full --strategy markdown`);
+ expect(out).toContain(orphanCommand(id));
expect(await failureKeys(engine, id)).toEqual([fullKey]);
- await runAction(engine, fresh);
+ await runAction(engine, orphanCommand(id));
expect(await failureKeys(engine, id)).toEqual([]);
} }), 240_000);
diff --git a/test/sync-managed-forbidden-flags-6696.test.ts b/test/sync-managed-forbidden-flags-6696.test.ts
index c6fc2e9a9f..b8cae3e2d3 100644
--- a/test/sync-managed-forbidden-flags-6696.test.ts
+++ b/test/sync-managed-forbidden-flags-6696.test.ts
@@ -85,7 +85,7 @@ test('the delegation ladder refuses before it looks for the serve\'s socket', as
const id = await fixture();
let socketLookups = 0;
const error = await quiet(() => maybeDelegateManagedSyncToServe(engine, ['--source', id, '--no-pull', '--include-gitignored'],
- { sourceId: id, noPull: true, includeGitignored: true, explicitProcessing: [], drain: true } as SyncOpts, {
+ { sourceId: id, noPull: true, includeGitignored: true, drain: true } as SyncOpts, {
config: { engine: 'postgres', database_url: 'postgresql://example.invalid/brain' },
probe: async () => ({ host_id: 'host', pid: 4242, nonce: 'n1', pid_ns: null, kind: 'serve', mode: 'full', started_at: new Date().toISOString(),
renewed_at: new Date().toISOString(), restart_required: false, root_barrier_age_ms: null, pool: null, host_json_path: '/tmp/host.json',
diff --git a/test/sync-owner-lane-processing-6696.test.ts b/test/sync-owner-lane-processing-6696.test.ts
index ebd3288a72..8b1172a344 100644
--- a/test/sync-owner-lane-processing-6696.test.ts
+++ b/test/sync-owner-lane-processing-6696.test.ts
@@ -1,16 +1,14 @@
/**
- * #6696 C1: the resident-owner sync lane (`writer_sync` → `runAuthenticatedSyncSlice`) keeps the in-process
- * processing-option contract.
+ * #6696 C1, revised by #6712 PR 1: the resident-owner sync lane (`writer_sync` → `runAuthenticatedSyncSlice`) resumes
+ * a cursor with the cursor's processing opt-outs.
*
* What these tests protect:
- * - a payload without an explicit list counts only its true-valued processing keys as typed: a `false` value is not
- * a typed flag (`explicitSyncProcessing` marks it explicit, which made a flagless resume conflict with a cursor
- * that stores `noEmbed=true` and refuse `invalid_params`);
- * - a list the caller supplied is preserved exactly instead of recomputed from the booleans: `[]` adopts the
- * cursor's stored options, and `['noEmbed']` with `noEmbed=false` is honored (it conflicts and refuses).
+ * - a `false` processing key is not an opt-in that conflicts with the cursor: a flagless resume of a cursor that
+ * stores `noEmbed=true` finishes it instead of refusing `invalid_params`;
+ * - an older CLI's `explicitProcessing` list is accepted and ignored (`WIRE_SKEW_WINDOWS.explicitProcessing`): the
+ * opt-outs are inherited OR-wise, so `['noEmbed']` with `noEmbed=false` finishes with `noEmbed` and reports it.
*
- * Regression that fails it: the owner lane recomputing the list with `explicitSyncProcessing`, or the wire refusing a
- * supplied list.
+ * Regression that fails it: the owner lane refusing a resume over processing options, or the wire refusing the list.
*/
import { afterAll, beforeAll, expect, test } from 'bun:test';
import { randomUUID } from 'node:crypto';
@@ -49,7 +47,7 @@ async function partialSource(): Promise<string> {
await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
await claimWorktree(engine, id, root);
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
- expect(await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true, explicitProcessing: [] } as SyncOpts, { maxPages: 1, maxMs: 1000 }))
+ expect(await performManagedSync(engine, { sourceId: id, noPull: true, noEmbed: true } as SyncOpts, { maxPages: 1, maxMs: 1000 }))
.toMatchObject({ status: 'partial' });
return id;
}
@@ -74,10 +72,10 @@ test('a payload without a list counts only true-valued keys as typed: noEmbed=fa
expect(await engine.getPage('notes/n2', { sourceId: id })).not.toBeNull();
}), 180_000);
-test('a supplied list is preserved: [] adopts the stored options, [\'noEmbed\'] with noEmbed=false is honored and refuses', async () => withEnv(env, async () => {
- const conflicting = await partialSource();
- expect(await slice({ sourceId: conflicting, noPull: true, noEmbed: false, explicitProcessing: ['noEmbed'] }))
- .toMatchObject({ error: { code: 'invalid_params', message: expect.stringContaining('processing options') } });
+test('an older CLI\'s list is accepted and ignored: [] and [\'noEmbed\'] with noEmbed=false both inherit the cursor\'s noEmbed', async () => withEnv(env, async () => {
+ const listed = await partialSource();
+ expect(await slice({ sourceId: listed, noPull: true, noEmbed: false, explicitProcessing: ['noEmbed'] })).toMatchObject({ status: 'first_sync', source_id: listed, inherited_options: ['noEmbed'] });
+ expect(await engine.getPage('notes/n2', { sourceId: listed })).not.toBeNull();
const adopting = await partialSource();
expect(await slice({ sourceId: adopting, noPull: true, explicitProcessing: [] })).toMatchObject({ status: 'first_sync', source_id: adopting });
}), 180_000);
diff --git a/test/sync-status-failure-detail-6513.test.ts b/test/sync-status-failure-detail-6513.test.ts
index 71b7c09acd..e6feb51ce6 100644
--- a/test/sync-status-failure-detail-6513.test.ts
+++ b/test/sync-status-failure-detail-6513.test.ts
@@ -56,7 +56,7 @@ async function fixture(engine: BrainEngine) {
await engine.executeRaw('INSERT INTO sources(id,name,local_path,config) VALUES($1,$1,$2,\'{}\')', [id, root]);
await claimWorktree(engine, id, root);
await engine.executeRaw('UPDATE persistence_brain SET enabled=true WHERE singleton=1');
- return { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true, explicitProcessing: [] } };
+ return { id, root, opts: { sourceId: id, noPull: true, noEmbed: true, noExtract: true } };
}
const leak = (value: unknown) => JSON.stringify(value, (_key, v) => typeof v === 'bigint' ? String(v) : v).includes(PRIVATE);
const PUBLIC = { origin: 'database_trigger', sqlstate: 'P0001', raiser: 'operator_hook_example', table: 'pages', reason: 'unknown', stage: 'publication' };