Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(persistence): preparation budget key family and preparation_deadlines kill switch (#6278)
garrytan07107b2803c2
diff --git a/src/commands/config.ts b/src/commands/config.tsindex ab2260e0ef..2df73ad80a 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -398,6 +398,15 @@ async function setConfigWithDecideHooks(engine: BrainEngine, key: string, value:const err = validateMaxClaimConfigValue(key, value);if (err) { console.error(`[config] ${err}`); process.exit(1); }}+ if (key.startsWith('persistence.') && (key.endsWith('_preparation_ms') || key === 'persistence.preparation_ceiling_ms' || key === 'persistence.max_preparation_attempts')) {+ const { readPreparationConfigValues, validatePreparationConfigValue } = await import('../core/persistence/preparation-budget.ts');+ const refusal = validatePreparationConfigValue(key, value, await readPreparationConfigValues(engine));+ if (refusal) {+ const { exitCliError, usageError } = await import('../cli/cli-error.ts');+ exitCliError(usageError(refusal.message, refusal.suggestion,+ { fix: { argv: ['gbrain', 'config', 'get', key], consent: [], actor: 'agent', why: 'Shows the value in effect; nothing was written.', requires_exclusive: false } }), 'config');+ }+ }if (key.startsWith('facts.')) await (await import('./config/facts-values.ts')).refuseInvalidFactsConfigValue(key, value);await engine.setConfig(key, value);if (key === 'auto_chronicle') await acknowledgeAutoChronicle(engine, value);diff --git a/src/core/config.ts b/src/core/config.tsindex 91ad05605c..ae987766c8 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1724,6 +1724,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['persistence.limits.principal_terminal_bytes', 'persistence.limits.brain_terminal_bytes','persistence.limits.brain_recovery_bytes', 'persistence.limits.worktree_recovery_bytes','persistence.receipt_retention_days', 'persistence.unbound_write', 'persistence.max_claim_ms', // #5254: persistence/unbound-source.ts; #6176: persistence/claim-phase.ts+ // #6278: preparation deadlines (persistence/preparation-budget.ts) and their kill switch (persistence/switches.ts)+ 'persistence.sync_preparation_ms', 'persistence.maintenance_preparation_ms', 'persistence.preparation_ceiling_ms', 'persistence.max_preparation_attempts',+ 'persistence.preparation_deadlines',// shared-skills migration inventory bounds (src/core/shared-skills/inventory-limits.ts)'shared_skills.inventory.max_files', 'shared_skills.inventory.max_total_bytes', 'shared_skills.inventory.max_file_bytes', 'shared_skills.inventory.max_entries','persistence.write_wait_ms', // #5232: file plane, persistence/write-wait.tsdiff --git a/src/core/persistence/preparation-budget.ts b/src/core/persistence/preparation-budget.tsnew file mode 100644index 0000000000..c3d20c9d51--- /dev/null+++ b/src/core/persistence/preparation-budget.ts@@ -0,0 +1,173 @@+/**+ * #6278: how long a claimed write may prepare before the consumer takes it+ * off its root, and how many such cut-offs a request survives.+ *+ * A preparation that never settles used to hold its root for as long as its+ * owner renewed the claim: only `remember` and intent-less page writes had the+ * 30 s budget. Every kind now has one. The budgets form one config family+ * (none repurposes `persistence.max_claim_ms`, doctor's warning threshold):+ *+ * - `persistence.sync_preparation_ms` (default 120000): a `managed_sync_*` member;+ * - `persistence.maintenance_preparation_ms` (default 120000): maintenance and+ * every other kind (the adoption preparer is put_page-sized);+ * - `persistence.preparation_ceiling_ms` (default 600000, 60000 to 3600000, at+ * least the larger budget plus 30 s): how long an abandoned preparation that+ * ignores cancellation may keep its root blocked, measured from the claim;+ * - `persistence.max_preparation_attempts` (default 2, 1 to 10): the request is+ * finished `failed`/`preparation_stalled` once its counter reaches it.+ *+ * `remember`, `put_page` and `edit_page` without an internal intent keep the+ * consumer's `preparationMs` (30 s). The deadlines sit behind the+ * `preparation_deadlines` write switch (switches.ts); off restores the old+ * predicate and never charges the counter. `racePreparation` is the one race+ * every caller uses (the consumer's single and group routes, and the sync's+ * out-of-consumer preparations): the budget wins even when the preparer+ * ignores its signal, and the late result is then the caller's to drop.+ */+import type { SqlEngine, WriteRequest } from './model.ts';++export const PREPARATION_BUDGET_KEYS = {+ syncMs: 'persistence.sync_preparation_ms',+ maintenanceMs: 'persistence.maintenance_preparation_ms',+ ceilingMs: 'persistence.preparation_ceiling_ms',+ maxAttempts: 'persistence.max_preparation_attempts',+} as const;+export type PreparationBudgetKey = keyof typeof PREPARATION_BUDGET_KEYS;+export const PREPARATION_BUDGET_CONFIG_KEYS: readonly string[] = Object.values(PREPARATION_BUDGET_KEYS);++export interface PreparationPolicy {+ syncMs: number;+ maintenanceMs: number;+ ceilingMs: number;+ maxAttempts: number;+}+export const DEFAULT_PREPARATION_POLICY: Readonly<PreparationPolicy> = Object.freeze({ syncMs: 120_000, maintenanceMs: 120_000, ceilingMs: 600_000, maxAttempts: 2 });+/** The ceiling must leave an abandoned preparation this much past the larger budget before the root is freed. */+export const PREPARATION_CEILING_GRACE_MS = 30_000;+const RANGES: Record<PreparationBudgetKey, { min: number; max: number; unit: string }> = {+ syncMs: { min: 1_000, max: 3_600_000, unit: 'milliseconds' },+ maintenanceMs: { min: 1_000, max: 3_600_000, unit: 'milliseconds' },+ ceilingMs: { min: 60_000, max: 3_600_000, unit: 'milliseconds' },+ maxAttempts: { min: 1, max: 10, unit: 'attempts' },+};++function parseWhole(raw: string | null | undefined): number | null {+ const text = raw?.trim() ?? '';+ return /^\d+$/.test(text) ? Number(text) : null;+}+/** The value of one key, or null when it is missing or out of range (the caller falls back to the default). */+export function parsePreparationBudget(name: PreparationBudgetKey, raw: string | null | undefined): number | null {+ const n = parseWhole(raw);+ return n !== null && n >= RANGES[name].min && n <= RANGES[name].max ? n : null;+}+/** The policy from the config rows read (key → value); a missing or invalid key keeps its default. */+export function resolvePreparationPolicy(configured: Map<string, string>): PreparationPolicy {+ const out = { ...DEFAULT_PREPARATION_POLICY };+ for (const [name, key] of Object.entries(PREPARATION_BUDGET_KEYS) as Array<[PreparationBudgetKey, string]>) {+ const value = parsePreparationBudget(name, configured.get(key));+ if (value !== null) out[name] = value;+ }+ // A ceiling below the budgets would free a root before its preparation could finish; it floors at the larger budget plus the grace.+ out.ceilingMs = Math.max(out.ceilingMs, Math.max(out.syncMs, out.maintenanceMs) + PREPARATION_CEILING_GRACE_MS);+ return out;+}++export interface PreparationConfigRefusal { message: string; suggestion: string; example: string }+/**+ * `config set` validation for the key family. `others` holds the current+ * values of the sibling keys so the ceiling rule is checked across keys. Null+ * when the value is valid or the key is another one.+ */+export function validatePreparationConfigValue(key: string, value: string, others: Map<string, string> = new Map()): PreparationConfigRefusal | null {+ const name = (Object.keys(PREPARATION_BUDGET_KEYS) as PreparationBudgetKey[]).find(candidate => PREPARATION_BUDGET_KEYS[candidate] === key);+ if (!name) return null;+ const range = RANGES[name];+ const n = parseWhole(value);+ if (n === null || n < range.min || n > range.max) {+ return { message: `${key} must be a whole number of ${range.unit} from ${range.min} to ${range.max} (default ${DEFAULT_PREPARATION_POLICY[name]}); got '${value}'. Nothing was written.`,+ suggestion: `Re-run with a value in range, for example gbrain config set ${key} ${DEFAULT_PREPARATION_POLICY[name]}.`, example: String(DEFAULT_PREPARATION_POLICY[name]) };+ }+ const merged = new Map(others);+ merged.set(key, value);+ const policy = resolvePreparationPolicyStrict(merged);+ const floor = Math.max(policy.syncMs, policy.maintenanceMs) + PREPARATION_CEILING_GRACE_MS;+ if (policy.ceilingMs < floor) {+ const fix = name === 'ceilingMs' ? `gbrain config set ${key} ${floor}` : `gbrain config set ${PREPARATION_BUDGET_KEYS.ceilingMs} ${Math.min(floor, RANGES.ceilingMs.max)}`;+ return { message: `${PREPARATION_BUDGET_KEYS.ceilingMs} (${policy.ceilingMs}) must be at least the larger preparation budget plus ${PREPARATION_CEILING_GRACE_MS} ms (${floor}); nothing was written.`,+ suggestion: `Raise the ceiling first (${fix}), or lower the budget so the ceiling stays above it.`, example: String(floor) };+ }+ return null;+}+/** Like `resolvePreparationPolicy` without the ceiling floor, for validation. */+function resolvePreparationPolicyStrict(configured: Map<string, string>): PreparationPolicy {+ const out = { ...DEFAULT_PREPARATION_POLICY };+ for (const [name, key] of Object.entries(PREPARATION_BUDGET_KEYS) as Array<[PreparationBudgetKey, string]>) {+ const value = parsePreparationBudget(name, configured.get(key));+ if (value !== null) out[name] = value;+ }+ return out;+}+/** The current values of the key family (for cross-key validation at `config set`). */+export async function readPreparationConfigValues(engine: SqlEngine): Promise<Map<string, string>> {+ const rows = await engine.executeRaw<{ key: string; value: string }>('SELECT key,value FROM config WHERE key = ANY($1::text[])', [PREPARATION_BUDGET_CONFIG_KEYS]).catch(() => []);+ return new Map(rows.map(row => [row.key, row.value]));+}++export type PreparationKind = 'foreground' | 'sync' | 'maintenance';+/** Which budget a request takes: the foreground 30 s, the sync member budget, or the maintenance budget for everything else. */+export function preparationKind(row: Pick<WriteRequest, 'operation' | 'intent'>): PreparationKind {+ const kind = row.intent?.kind;+ if (row.operation === 'remember' || (row.operation === 'put_page' || row.operation === 'edit_page') && !kind) return 'foreground';+ return String(kind ?? '').startsWith('managed_sync_') ? 'sync' : 'maintenance';+}+export function preparationBudgetMs(row: Pick<WriteRequest, 'operation' | 'intent'>, policy: PreparationPolicy, foregroundMs: number): number {+ const kind = preparationKind(row);+ return kind === 'foreground' ? foregroundMs : kind === 'sync' ? policy.syncMs : policy.maintenanceMs;+}++/** What `racePreparation` yields when the budget passes before the work settles. */+export const PREPARATION_DEADLINE: unique symbol = Symbol('preparation_deadline');+/**+ * Runs `work` with a signal that aborts `{ code: 'preparation_deadline' }` at+ * the budget and yields PREPARATION_DEADLINE then, whether or not the work+ * honours the signal; the work keeps running and the caller owns it (it must+ * never publish a late result). `signal` (an outer cancellation) aborts the+ * work's signal too and rejects the race with the outer reason. The budget is+ * measured by `now`, so a synchronous late preparation that outruns the timer+ * still reads as a deadline.+ */+export async function racePreparation<T>(work: (signal: AbortSignal) => Promise<T>, budgetMs: number,+ opts: { signal?: AbortSignal; now?: () => number; onDeadline?: () => void } = {}): Promise<{ result: T } | { deadline: typeof PREPARATION_DEADLINE; work: Promise<T> }> {+ const now = opts.now ?? (() => performance.now());+ const abort = new AbortController();+ const deadline = Promise.withResolvers<typeof PREPARATION_DEADLINE>();+ let expired = false;+ // The deadline settles before the abort reaches the work, so a preparer that rejects on abort never wins the race.+ const expire = () => {+ if (expired) return;+ expired = true;+ deadline.resolve(PREPARATION_DEADLINE);+ if (!abort.signal.aborted) abort.abort({ code: 'preparation_deadline' });+ opts.onDeadline?.();+ };+ const timer = setTimeout(expire, budgetMs);+ const outer = Promise.withResolvers<never>();+ const onOuter = () => { abort.abort(opts.signal?.reason); outer.reject(opts.signal?.reason); };+ if (opts.signal?.aborted) onOuter(); else opts.signal?.addEventListener('abort', onOuter, { once: true });+ outer.promise.catch(() => undefined);+ const started = now();+ const run = (async () => work(abort.signal))();+ run.catch(() => undefined);+ const late = () => expired || now() - started >= budgetMs;+ try {+ const won = await Promise.race([run.then(result => ({ result })), deadline.promise.then(deadline => ({ deadline, work: run })), outer.promise]);+ if ('result' in won && late()) { expire(); return { deadline: PREPARATION_DEADLINE, work: run }; }+ return won;+ } catch (error) {+ if (!opts.signal?.aborted && late()) { expire(); return { deadline: PREPARATION_DEADLINE, work: run }; }+ throw error;+ } finally {+ clearTimeout(timer);+ opts.signal?.removeEventListener('abort', onOuter);+ }+}diff --git a/src/core/persistence/switches.ts b/src/core/persistence/switches.tsindex 837bdc8b97..221de777f3 100644--- a/src/core/persistence/switches.ts+++ b/src/core/persistence/switches.ts@@ -9,6 +9,7 @@* remote operation writes config), so a remote caller cannot flip a switch.*/import type { SqlEngine } from './model.ts';+import { DEFAULT_PREPARATION_POLICY, PREPARATION_BUDGET_CONFIG_KEYS, resolvePreparationPolicy, type PreparationPolicy } from './preparation-budget.ts';export const WRITE_SWITCHES = {/** Phase 4.1/4.3/4.4: single page writes publish as a group of one, the own admission claims directly, publication reuses a warm connection. */@@ -19,6 +20,8 @@ export const WRITE_SWITCHES = {waive_batch: { key: 'sync.waive_batch', env: 'GBRAIN_SYNC_WAIVE_BATCH' },/** Phase 4.5: a foreground write goes ahead of queued sync groups that do not name its page; off restores the FIFO and the sync side's pauses. */foreground_priority: { key: 'sync.foreground_priority', env: 'GBRAIN_SYNC_FOREGROUND_PRIORITY' },+ /** #6278: every preparation has a deadline and a counted attempt; off restores the 30 s budget for remember/put_page/edit_page only and never counts. */+ preparation_deadlines: { key: 'persistence.preparation_deadlines', env: 'GBRAIN_PREPARATION_DEADLINES' },} as const;export type WriteSwitch = keyof typeof WRITE_SWITCHES;export type WriteSwitches = Record<WriteSwitch, boolean>;@@ -27,16 +30,19 @@ export const SWITCH_TTL_MS = 5000;const off = (value: string | null | undefined) => typeof value === 'string' && /^(0|false)$/i.test(value.trim());const on = (value: string | null | undefined) => typeof value === 'string' && /^(1|true)$/i.test(value.trim());-const snapshots = new WeakMap<object, { at: number; generation: number; read: Promise<WriteSwitches> }>();+/** One snapshot read: the switches plus the #6278 preparation budgets (preparation-budget.ts), so a claim never reads config on its own. */+export interface WriteSwitchSnapshot { switches: WriteSwitches; preparation: PreparationPolicy }+const snapshots = new WeakMap<object, { at: number; generation: number; read: Promise<WriteSwitchSnapshot> }>();let generation = 0;+const SNAPSHOT_KEYS: readonly string[] = [...WRITE_SWITCH_KEYS, ...PREPARATION_BUDGET_CONFIG_KEYS];-function resolve(configured: Map<string, string>): WriteSwitches {+function resolve(configured: Map<string, string>): WriteSwitchSnapshot {const out = {} as WriteSwitches;for (const [name, { key, env }] of Object.entries(WRITE_SWITCHES) as Array<[WriteSwitch, { key: string; env: string }]>) {const fromEnv = process.env[env];out[name] = off(fromEnv) ? false : on(fromEnv) ? true : !off(configured.get(key));}- return out;+ return { switches: out, preparation: resolvePreparationPolicy(configured) };}/** Read-through views of an engine (preparation config, pre-admission cache) and the engine they read through. */@@ -50,16 +56,24 @@ export function viewedEngine<T extends object>(engine: T): T { return (views.get* `signal` cancels a read this call starts (the consumer's tick reads under its phase deadline).*/export function readWriteSwitches(viewed: SqlEngine, opts: { now?: () => number; signal?: AbortSignal } = {}): Promise<WriteSwitches> {+ return readWriteSwitchSnapshot(viewed, opts).then(snapshot => snapshot.switches);+}+/** The switches and the preparation budgets of `engine`'s brain, from the same snapshot. */+export function readWriteSwitchSnapshot(viewed: SqlEngine, opts: { now?: () => number; signal?: AbortSignal } = {}): Promise<WriteSwitchSnapshot> {const now = opts.now ?? Date.now;const engine = viewedEngine(viewed);const held = snapshots.get(engine);if (held && held.generation === generation && now() - held.at < SWITCH_TTL_MS) return held.read;- const read = engine.executeRaw<{ key: string; value: string }>('SELECT key,value FROM config WHERE key = ANY($1::text[])', [WRITE_SWITCH_KEYS], { signal: opts.signal })+ const read = engine.executeRaw<{ key: string; value: string }>('SELECT key,value FROM config WHERE key = ANY($1::text[])', [SNAPSHOT_KEYS], { signal: opts.signal }).then(rows => resolve(new Map(rows.map(row => [row.key, row.value]))));snapshots.set(engine, { at: now(), generation, read });read.catch(() => { if (snapshots.get(engine)?.read === read) snapshots.delete(engine); });return read;}+/** The preparation budgets in effect (defaults when the read fails). */+export async function readPreparationPolicy(engine: SqlEngine): Promise<PreparationPolicy> {+ return readWriteSwitchSnapshot(engine).then(snapshot => snapshot.preparation, () => ({ ...DEFAULT_PREPARATION_POLICY }));+}export async function writeSwitchOn(engine: SqlEngine, name: WriteSwitch): Promise<boolean> {return (await readWriteSwitches(engine))[name];diff --git a/test/persistence-preparation-budget.test.ts b/test/persistence-preparation-budget.test.tsnew file mode 100644index 0000000000..86c2b4bd71--- /dev/null+++ b/test/persistence-preparation-budget.test.ts@@ -0,0 +1,134 @@+/**+ * #6278: the preparation budget family (preparation-budget.ts) and its kill+ * switch (switches.ts). Protects: the per-kind budget table, the config key+ * ranges and the ceiling rule (ceiling >= larger budget + 30 s) as `config set`+ * and the snapshot resolve them, the default-on `preparation_deadlines`+ * switch, and `racePreparation`, which yields the deadline whether or not the+ * preparer honours its signal and never lets a late result through. Fails+ * when a key silently falls back without validation, when the switch reads+ * off by default, or when a signal-ignoring preparer outlives its budget.+ * Why not covered elsewhere: the consumer suites drive whole writes; these+ * pin the table and the race in milliseconds with no datastore.+ */+import { afterEach, describe, expect, test } from 'bun:test';+import { DEFAULT_PREPARATION_POLICY, PREPARATION_BUDGET_KEYS, PREPARATION_DEADLINE, preparationBudgetMs, preparationKind, racePreparation,+ resolvePreparationPolicy, validatePreparationConfigValue } from '../src/core/persistence/preparation-budget.ts';+import { readPreparationPolicy, readWriteSwitches, resetWriteSwitches, WRITE_SWITCHES } from '../src/core/persistence/switches.ts';+import { withEnv } from './helpers/with-env.ts';++const sleep = (ms: number) => new Promise<void>(resolve => setTimeout(resolve, ms));++describe('budget table', () => {+ const policy = { ...DEFAULT_PREPARATION_POLICY, syncMs: 1111, maintenanceMs: 2222 };+ test('remember and intent-less put_page/edit_page keep the foreground budget', () => {+ for (const row of [{ operation: 'remember', intent: null }, { operation: 'put_page', intent: {} }, { operation: 'edit_page', intent: null }]) {+ expect(preparationKind(row)).toBe('foreground');+ expect(preparationBudgetMs(row, policy, 30_000)).toBe(30_000);+ }+ });+ test('managed sync members take the sync budget; maintenance and every other kind the maintenance budget', () => {+ expect(preparationBudgetMs({ operation: 'submit_job', intent: { kind: 'managed_sync_import' } }, policy, 30_000)).toBe(1111);+ expect(preparationBudgetMs({ operation: 'submit_job', intent: { kind: 'managed_sync_checkpoint' } }, policy, 30_000)).toBe(1111);+ expect(preparationBudgetMs({ operation: 'submit_job', intent: { kind: 'managed_maintenance_adopt_fact_fence' } }, policy, 30_000)).toBe(2222);+ expect(preparationBudgetMs({ operation: 'put_page', intent: { kind: 'canonical_reconcile' } }, policy, 30_000)).toBe(2222);+ expect(preparationBudgetMs({ operation: 'takes_add', intent: null }, policy, 30_000)).toBe(2222);+ });+});++describe('config key family', () => {+ test('defaults: 120 s budgets, 600 s ceiling, 2 attempts', () => {+ expect(resolvePreparationPolicy(new Map())).toEqual({ syncMs: 120_000, maintenanceMs: 120_000, ceilingMs: 600_000, maxAttempts: 2 });+ });+ test('configured values are read; invalid ones keep their default; the ceiling floors at the larger budget plus 30 s', () => {+ const policy = resolvePreparationPolicy(new Map([+ [PREPARATION_BUDGET_KEYS.syncMs, '300000'], [PREPARATION_BUDGET_KEYS.maintenanceMs, 'abc'],+ [PREPARATION_BUDGET_KEYS.ceilingMs, '60000'], [PREPARATION_BUDGET_KEYS.maxAttempts, '3']]));+ expect(policy).toEqual({ syncMs: 300_000, maintenanceMs: 120_000, ceilingMs: 330_000, maxAttempts: 3 });+ expect(resolvePreparationPolicy(new Map([[PREPARATION_BUDGET_KEYS.maxAttempts, '11']])).maxAttempts).toBe(2);+ });+ test('config set refuses out-of-range values with the range and example, and ignores other keys', () => {+ expect(validatePreparationConfigValue('persistence.max_claim_ms', 'anything')).toBeNull();+ expect(validatePreparationConfigValue(PREPARATION_BUDGET_KEYS.syncMs, '120000')).toBeNull();+ expect(validatePreparationConfigValue(PREPARATION_BUDGET_KEYS.maxAttempts, '0')).toMatchObject({ message: expect.stringContaining('from 1 to 10'), example: '2' });+ expect(validatePreparationConfigValue(PREPARATION_BUDGET_KEYS.maxAttempts, '2.5')?.message).toContain('whole number');+ expect(validatePreparationConfigValue(PREPARATION_BUDGET_KEYS.ceilingMs, '59999')?.message).toContain('from 60000 to 3600000');+ expect(validatePreparationConfigValue(PREPARATION_BUDGET_KEYS.ceilingMs, '3600001')?.message).toContain('Nothing was written');+ });+ test('the ceiling must stay at least the larger budget plus 30 s, checked across the sibling keys', () => {+ expect(validatePreparationConfigValue(PREPARATION_BUDGET_KEYS.ceilingMs, '149999')).toMatchObject({ example: '150000' });+ expect(validatePreparationConfigValue(PREPARATION_BUDGET_KEYS.ceilingMs, '150000')).toBeNull();+ const others = new Map([[PREPARATION_BUDGET_KEYS.ceilingMs, '200000']]);+ expect(validatePreparationConfigValue(PREPARATION_BUDGET_KEYS.syncMs, '170000', others)).toBeNull();+ expect(validatePreparationConfigValue(PREPARATION_BUDGET_KEYS.syncMs, '170001', others)?.suggestion).toContain(`gbrain config set ${PREPARATION_BUDGET_KEYS.ceilingMs} 200001`);+ expect(validatePreparationConfigValue(PREPARATION_BUDGET_KEYS.maintenanceMs, '600000')?.message).toContain('600000');+ });+});++describe('preparation_deadlines switch', () => {+ afterEach(() => resetWriteSwitches());+ const engineWith = (rows: Array<{ key: string; value: string }>) => ({ executeRaw: async () => rows as never[] });+ test('is on by default, off through config or environment, and shares the budget snapshot', async () => {+ expect(WRITE_SWITCHES.preparation_deadlines).toEqual({ key: 'persistence.preparation_deadlines', env: 'GBRAIN_PREPARATION_DEADLINES' });+ const engine = engineWith([{ key: PREPARATION_BUDGET_KEYS.syncMs, value: '5000' }]);+ expect((await readWriteSwitches(engine)).preparation_deadlines).toBe(true);+ expect(await readPreparationPolicy(engine)).toMatchObject({ syncMs: 5000, maintenanceMs: 120_000 });+ resetWriteSwitches();+ expect((await readWriteSwitches(engineWith([{ key: 'persistence.preparation_deadlines', value: 'false' }]))).preparation_deadlines).toBe(false);+ resetWriteSwitches();+ await withEnv({ GBRAIN_PREPARATION_DEADLINES: '0' }, async () => {+ expect((await readWriteSwitches(engineWith([]))).preparation_deadlines).toBe(false);+ });+ });+ test('a failed snapshot read leaves the defaults in effect', async () => {+ const failing = { executeRaw: async () => { throw new Error('connection reset'); } };+ expect(await readPreparationPolicy(failing)).toEqual(DEFAULT_PREPARATION_POLICY);+ });+});++describe('racePreparation', () => {+ test('a preparation inside its budget yields its result and never aborts', async () => {+ let signal: AbortSignal | undefined;+ const raced = await racePreparation(async s => { signal = s; await sleep(10); return 'prepared'; }, 500);+ expect(raced).toEqual({ result: 'prepared' });+ expect(signal?.aborted).toBe(false);+ });+ test('a preparer that honours its signal is cut off at the budget: the deadline wins, not its abort rejection', async () => {+ const raced = await racePreparation(async signal => new Promise<string>((_, reject) => signal.addEventListener('abort', () => reject(signal.reason), { once: true })), 20);+ expect('deadline' in raced && raced.deadline).toBe(PREPARATION_DEADLINE);+ if ('deadline' in raced) await expect(raced.work).rejects.toMatchObject({ code: 'preparation_deadline' });+ });+ test('a preparer that ignores its signal is cut off at the budget too, and its late result is left to the caller', async () => {+ const release = Promise.withResolvers<string>();+ let seen = 0;+ const started = performance.now();+ const raced = await racePreparation(async () => release.promise, 20, { onDeadline: () => { seen++; } });+ expect(performance.now() - started).toBeGreaterThanOrEqual(15);+ expect('deadline' in raced).toBe(true);+ expect(seen).toBe(1);+ release.resolve('late');+ if ('deadline' in raced) expect(await raced.work).toBe('late');+ });+ test('a synchronous preparation that outruns the timer still reads as a deadline (resolve and reject)', async () => {+ for (const reject of [false, true]) {+ const raced = await racePreparation(async () => {+ const until = performance.now() + 40;+ while (performance.now() < until) { /* busy */ }+ if (reject) throw new DOMException('late', 'AbortError');+ return 'late';+ }, 10);+ expect('deadline' in raced).toBe(true);+ }+ });+ test('a real failure inside the budget propagates', async () => {+ await expect(racePreparation(async () => { throw new Error('boom'); }, 500)).rejects.toThrow('boom');+ });+ test('an outer cancellation aborts the work with its own reason and rejects the race', async () => {+ const outer = new AbortController();+ let reason: unknown;+ const racing = racePreparation(async signal => new Promise<never>((_, reject) => signal.addEventListener('abort', () => { reason = signal.reason; reject(signal.reason); }, { once: true })),+ 5_000, { signal: outer.signal });+ outer.abort({ code: 'consumer_stopping' });+ await expect(racing).rejects.toMatchObject({ code: 'consumer_stopping' });+ expect(reason).toMatchObject({ code: 'consumer_stopping' });+ });+});