diff --git a/RELEASES.md b/RELEASES.md index 89bf38e7..03d7283a 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -31,6 +31,68 @@ is sometimes cited as a 7.x removal — those methods never existed on 7.x; the --- +## v8.10.1 — 2026-07-24 (the no-hot-retry contract + warm()'s metadata surface under native providers) + +From a production incident: a native-provider op ground 38-40s inside a transaction, +blew the ~32s apply-phase budget, was rolled back (zero loss, by design), and a +downstream pipeline hot-retried the identical operation into a 6-minute, 100%-CPU +storm. Investigation confirmed Brainy itself never auto-retries a timed-out +transaction — the storm was entirely the consumer's own retry loop, driven by a +"retryable" doc-prose claim with no machine-readable contract to branch on. This +release closes that contract gap and, separately, fixes a real `warm()` reporting gap +surfaced by the same investigation. + +- **`TransactionTimeoutError` is now a machine-readable no-hot-retry contract.** Two + new typed, always-`true` fields replace prose-only guidance: + - `retryable: true` — the operation MAY succeed on a later attempt, once the + underlying slowness resolves or the budget is deliberately raised + (`transactionBudgetFloorMs`, or a batch's own `timeoutMs` override). + - `hotRetryUnsafe: true` — an immediate, identical retry re-pays the FULL cost of + the work that just timed out (it does not resume partway) and can cascade into + exactly the CPU storm above. **Never loop on this error.** The documented pattern + is a latch, not a retry loop: + ``` + on TransactionTimeoutError: + record { at: Date.now(), error } + rethrow loudly to your own caller + hold a cooldown window before any re-attempt + clear the latch only on a subsequent success + ``` + - `context` (unchanged, now fully documented) carries the backoff inputs: + `timeoutMs`, `operationIndex`, `elapsedMs`, `totalOperations`, `operationName`. + - Every "retryable" doc-prose site referencing this error (`transact()`'s + `timeoutMs` option, `transactionBudgetFloorMs`, `Transaction.execute()`) now + points at these fields instead of bare prose. + - Regression-pinned: the engine never internally re-drives a timed-out operation + (verified via an execution counter through both the single-op write path and + `add()`'s upsert-race retry loop), so this has always been true — it is now + provable and typed. +- **Dead code removed**: `TransactionManager.executeTransactionWithResult()` had zero + callers in this codebase and is deleted. +- **`brain.warm()`'s metadata surface now routes through the ACTIVE provider.** A + production deployment's warm report showed `metadata: 'unavailable'` under a native + metadata provider — the previous logic only duck-typed the built-in JS manager's + `hydrateAll()` method, which a native provider has no reason to implement. The + metadata provider contract (`MetadataIndexProvider`, `src/plugin.ts`) gains an + optional `warm?(): Promise` hook, mirroring the existing vector and graph + provider hooks. `brain.warm()` now checks the active provider's own `warm()` FIRST, + falls back to the JS manager's `hydrateAll()` when absent, and only reports + `'unavailable'` when neither exists — never `init()` as a stand-in, since a native + provider's `init()` may be a cheap verify rather than a real warm. A native + provider lights this surface up the same way `@soulcraft/cor` already lights the + vector and graph surfaces: implement `warm()` on its metadata provider. +- **New: `brain.maintenanceDebt()`** — the observability seam so an operator sees a + provider's outstanding background maintenance work (pending bytes/items, last pass + outcome, whether it's converging) BEFORE it grinds into the kind of budget-busting + op this release's timeout contract exists for, instead of discovering it as a CPU + storm. It is a pure passthrough: brainy applies no thresholds, no polling, and no + estimation — it calls each active provider's own optional `maintenanceDebt?()` hook + (vector, metadata, graph — the same three contracts `warm?()` lives on) and reports + the payload verbatim, or `'unavailable'` when a surface's provider doesn't track + debt. Useful as a pre-warm/post-warm check or a boot gate. `@soulcraft/cor` does not + yet implement the hook as of this release — expect it on cor's next release; until + then all three surfaces honestly report `'unavailable'`. + ## Unreleased (the warm contract: cold-restart writes stop paying demand-load latency) From a production deployment's cold-restart incident: the FIRST writes after every diff --git a/src/brainy.ts b/src/brainy.ts index 37b6e491..007cdb32 100644 --- a/src/brainy.ts +++ b/src/brainy.ts @@ -65,7 +65,8 @@ import type { OpaqueIdSet, AtGenerationVectors, VectorIndexProvider, - GraphIndexProvider + GraphIndexProvider, + ProviderMaintenanceDebt } from './plugin.js' import type { BrainyPlugin, @@ -424,6 +425,30 @@ export interface WarmReport { totalDurationMs: number } +/** + * @description Result of {@link Brainy.maintenanceDebt}: one outcome per + * index surface, mirroring {@link WarmReport}'s shape. + * - `'reported'` — the active provider for this surface implements + * `maintenanceDebt?()` and its {@link ProviderMaintenanceDebt} payload is + * attached verbatim under `debt`. + * - `'unavailable'` — the active provider does not implement the hook, so + * nothing is known; brainy never estimates or infers a payload on its + * behalf. + */ +export type MaintenanceDebtOutcome = 'reported' | 'unavailable' + +/** + * @description Per-surface result of {@link Brainy.maintenanceDebt}. Brainy + * performs no thresholding, polling, or estimation over this data — it is a + * pure passthrough of each active provider's own self-report (the provider + * owns the numbers; the operator owns the policy). + */ +export interface MaintenanceDebtReport { + vector: { outcome: MaintenanceDebtOutcome; debt?: ProviderMaintenanceDebt } + metadata: { outcome: MaintenanceDebtOutcome; debt?: ProviderMaintenanceDebt } + graph: { outcome: MaintenanceDebtOutcome; debt?: ProviderMaintenanceDebt } +} + /** * How long a failed aggregation-backfill walk suppresses fresh walk attempts. * Within the window, queries rethrow the recorded failure instantly (loud, @@ -14313,9 +14338,16 @@ export class Brainy implements BrainyInterface { * *some* backing storage as a side effect but is reported honestly as * `'probed'`, never `'warmed'`. An empty index or unknown dimension has * nothing to probe (`'unavailable'`). - * - **Metadata**: full hydration — every persisted field's sparse index is - * loaded from storage (`MetadataIndexManager.hydrateAll()`), not just the - * heuristic common-fields subset `init()` warms. + * - **Metadata**: calls the provider's own `warm?()` when the active + * `'metadataIndex'` provider implements it (`'warmed'`) — the seam a + * native metadata provider lights up so it is not duck-typed against the + * JS manager's method. Otherwise falls back to full hydration on the + * built-in JS manager — every persisted field's sparse index is loaded + * from storage (`MetadataIndexManager.hydrateAll()`), not just the + * heuristic common-fields subset `init()` warms — and reports `'warmed'`. + * Neither seam present → `'unavailable'` (honest: `init()` is never used + * as a substitute here, since a native provider's `init()` may be a + * cheap verify rather than a real warm). * - **Graph**: calls the provider's own `warm?()` when the active graph * provider implements it; otherwise re-runs its existing eager cold-load * `init()` seam (idempotent — the JS adjacency index's `init()` already @@ -14371,12 +14403,23 @@ export class Brainy implements BrainyInterface { // --- Metadata -------------------------------------------------------- const metadataStart = Date.now() let metadataOutcome: WarmOutcome + const metadataProvider = this.metadataIndex as unknown as MetadataIndexProvider const metadataWithHydrate = this.metadataIndex as unknown as { hydrateAll?: () => Promise } - if (typeof metadataWithHydrate.hydrateAll === 'function') { + if (typeof metadataProvider.warm === 'function') { + // Active provider (e.g. a native metadata index) declares its own warm + // seam — route through it FIRST so a native provider's warmth is + // reported honestly instead of being duck-typed against the JS + // manager's hydrateAll(), which a native provider does not implement. + await metadataProvider.warm() + metadataOutcome = 'warmed' + } else if (typeof metadataWithHydrate.hydrateAll === 'function') { + // Built-in JS manager path — full sparse-index hydration. await metadataWithHydrate.hydrateAll() metadataOutcome = 'warmed' } else { - // No hydration seam on this metadata provider — nothing to run. + // No hydration seam on this metadata provider — nothing to run. (No + // init() fallback here: init() on a native provider may be a cheap + // verify, and reporting that as warmth would lie.) metadataOutcome = 'unavailable' } const metadataDurationMs = Date.now() - metadataStart @@ -14410,6 +14453,63 @@ export class Brainy implements BrainyInterface { } } + /** + * Read each index surface's self-reported outstanding maintenance work — + * the observability seam so an operator sees a grind coming (rising + * pending bytes/items, a stalled background pass) instead of discovering + * it as a CPU storm or a transaction blowing its budget mid-flight (see + * {@link TransactionTimeoutError}). + * + * PURE PASSTHROUGH: for each of vector/metadata/graph, this calls ONLY the + * ACTIVE provider's own `maintenanceDebt?()` hook (the same per-surface + * provider resolution {@link Brainy.warm} uses) and reports its + * {@link ProviderMaintenanceDebt} payload verbatim. There is no JS-side + * fallback computation, no threshold evaluation, and no polling — brainy + * surfaces the truth the provider measured; the provider owns the numbers + * and the operator owns the policy (what threshold matters, what action to + * take). A surface whose active provider does not implement the hook + * reports `'unavailable'` — never a guessed or zeroed payload. + * + * @returns A {@link MaintenanceDebtReport}: per-surface outcome + payload. + * @example + * ```typescript + * const debt = await brain.maintenanceDebt() + * if (debt.metadata.outcome === 'reported' && debt.metadata.debt?.pendingBytes) { + * console.log('metadata pending bytes:', debt.metadata.debt.pendingBytes) + * } + * ``` + */ + async maintenanceDebt(): Promise { + await this.ensureInitialized({ needs: ['vector', 'metadata', 'graph'] }) + + // --- Vector --------------------------------------------------------- + const vectorProvider = this.index as VectorIndexProvider & { + maintenanceDebt?: () => Promise + } + const vector = + typeof vectorProvider.maintenanceDebt === 'function' + ? { outcome: 'reported' as const, debt: await vectorProvider.maintenanceDebt() } + : { outcome: 'unavailable' as const } + + // --- Metadata -------------------------------------------------------- + const metadataProvider = this.metadataIndex as unknown as MetadataIndexProvider + const metadata = + typeof metadataProvider.maintenanceDebt === 'function' + ? { outcome: 'reported' as const, debt: await metadataProvider.maintenanceDebt() } + : { outcome: 'unavailable' as const } + + // --- Graph ------------------------------------------------------------- + const graphProvider = this.graphIndex as GraphIndexProvider & { + maintenanceDebt?: () => Promise + } + const graph = + typeof graphProvider.maintenanceDebt === 'function' + ? { outcome: 'reported' as const, debt: await graphProvider.maintenanceDebt() } + : { outcome: 'unavailable' as const } + + return { vector, metadata, graph } + } + /** * Explicitly warm up the embedding engine * diff --git a/src/index.ts b/src/index.ts index 00adc191..e60739f7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -31,6 +31,11 @@ export type { DiagnosticsResult } from './brainy.js' // brain.warm() — eager index/storage readiness report (per-surface honest // outcome + timing). See the WarmReport JSDoc in brainy.ts. export type { WarmReport, WarmOutcome } from './brainy.js' +// brain.maintenanceDebt() — per-surface passthrough of each active +// provider's self-reported background maintenance debt. See the +// MaintenanceDebtReport JSDoc in brainy.ts and ProviderMaintenanceDebt in +// plugin.ts for the measure-only-what-you-track contract. +export type { MaintenanceDebtReport, MaintenanceDebtOutcome } from './brainy.js' export type { GraphAuditReport, GraphAuditDiscrepancy @@ -227,6 +232,11 @@ export type { FamilyStamp, StampMembers, StampVerdict } from './db/familyStamp.j export { isVersionedIndexProvider } from './plugin.js' export type { VersionedIndexProvider } from './plugin.js' export type { ProviderInvariantReport, InvariantResult, InvariantHeal } from './plugin.js' +// Optional provider self-report of outstanding background maintenance work +// (compaction, deferred writes, etc.) — the payload type for +// brain.maintenanceDebt(). See the measure-only-what-you-track contract on +// ProviderMaintenanceDebt in plugin.ts. +export type { ProviderMaintenanceDebt } from './plugin.js' // Optional native graph-acceleration engine (cor 3.0) — the published provider // contract + its columnar wire types. Brainy feature-detects an implementation // and falls back to its pure-TS adjacency when absent. diff --git a/src/plugin.ts b/src/plugin.ts index 02639955..ce973386 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -171,6 +171,37 @@ export interface ProviderInvariantReport { durationMs: number } +/** + * @description A provider's self-report of its own outstanding background + * maintenance work (compaction, deferred writes, a build-new→verify→swap in + * flight, etc.) — the observability seam so an operator sees a grind coming + * (rising pending bytes/items, a stalled pass) instead of discovering it as a + * CPU storm or a timeout under transaction budget pressure. Every field is + * OPTIONAL and every field is a MEASUREMENT: a provider reports ONLY what it + * actually tracks, never an estimate dressed up as a fact. Absence of the + * {@link VectorIndexProvider.maintenanceDebt} / + * {@link GraphIndexProvider.maintenanceDebt} / + * {@link MetadataIndexProvider.maintenanceDebt} hook itself means the + * provider does not track debt at all — brainy reports that surface + * `'unavailable'` rather than inventing zeros. Brainy performs NO threshold + * checks, NO polling, and NO JS-side estimation over this payload — it is a + * pure passthrough via {@link Brainy.maintenanceDebt}; the provider owns the + * numbers and the operator owns the policy (what threshold matters, what to + * do about it). + */ +export interface ProviderMaintenanceDebt { + /** Bytes of outstanding/unmerged work, if the provider measures it (e.g. unflushed writes, unmerged segments). */ + pendingBytes?: number + /** Count of outstanding items (records, segments, nodes) awaiting the provider's background pass. */ + pendingItems?: number + /** Epoch millis when the provider's last maintenance pass finished, if it tracks one. */ + lastPassCompletedAt?: number + /** How the last pass ended, if the provider tracks pass outcomes. */ + lastPassOutcome?: 'completed' | 'partial' | 'failed' + /** `true` if the provider's own measurements show debt trending down (making progress); `false` if flat or growing; omitted if the provider can't tell. */ + converging?: boolean +} + /** * The `'metadataIndex'` provider — a drop-in for `MetadataIndexManager`. * Brainy calls this surface via `this.metadataIndex.*` (see `brainy.ts`) and @@ -181,6 +212,34 @@ export interface MetadataIndexProvider { flush(): Promise rebuild(): Promise + /** + * @description OPTIONAL. Eagerly load/fault-in backing storage (e.g. mmap + * pretouch, full sparse-index hydration) so first queries run at + * steady-state cost. Optional; absence means the provider demand-loads. + * Mirrors {@link GraphIndexProvider.warm} / the vector provider's `warm?()` + * (`src/plugin.ts` VectorIndexProvider). Distinct from `init()`: `init` is + * required and runs once automatically during brain startup; `warm` is a + * separate, explicit step a caller opts into via `brain.warm()` (or + * `warmOnOpen`) to pre-pay demand-load cost `init` left lazy. Idempotent — + * calling it more than once must be safe and cheap on a brain that is + * already warm. A provider that already loads everything eagerly in + * `init()` may implement `warm` as a no-op or omit it — `brain.warm()` + * falls back to the built-in JS manager's `hydrateAll()` duck-type when + * absent, and to an honest `'unavailable'` when neither exists. + */ + warm?(): Promise + + /** + * @description OPTIONAL self-reported {@link ProviderMaintenanceDebt} — + * the observability seam so an operator sees outstanding background + * maintenance work (e.g. unmerged postings) BEFORE it grinds a transaction + * into a budget-busting op. Absence means this provider does not track + * debt; `brain.maintenanceDebt()` reports this surface `'unavailable'` + * rather than guessing. See {@link ProviderMaintenanceDebt} for the + * measure-only-what-you-track contract. + */ + maintenanceDebt?(): Promise + /** * @description OPTIONAL honest durability signal (readiness contract, * mirrors `isReady?()` on the graph and vector providers). `true` ⇔ the @@ -395,6 +454,18 @@ export interface GraphIndexProvider { */ warm?(): Promise + /** + * @description OPTIONAL self-reported {@link ProviderMaintenanceDebt} — + * the observability seam so an operator sees outstanding background + * maintenance work (e.g. a build-new→verify→swap in flight, unmerged + * adjacency segments) BEFORE it grinds a transaction into a + * budget-busting op. Absence means this provider does not track debt; + * `brain.maintenanceDebt()` reports this surface `'unavailable'` rather + * than guessing. See {@link ProviderMaintenanceDebt} for the + * measure-only-what-you-track contract. + */ + maintenanceDebt?(): Promise + /** * @description OPTIONAL. A native provider returns true from the moment its * `init()` detects a large epoch-drift until its background @@ -1057,6 +1128,18 @@ export interface VectorIndexProvider { */ warm?(): Promise + /** + * @description OPTIONAL self-reported {@link ProviderMaintenanceDebt} — + * the observability seam so an operator sees outstanding background + * maintenance work (e.g. unflushed writes, a pending rebuild) BEFORE it + * grinds a transaction into a budget-busting op. Absence means this + * provider does not track debt; `brain.maintenanceDebt()` reports this + * surface `'unavailable'` rather than guessing. See + * {@link ProviderMaintenanceDebt} for the measure-only-what-you-track + * contract. + */ + maintenanceDebt?(): Promise + /** * @description OPTIONAL honest durability signal (readiness contract, * mirrors {@link GraphIndexProvider.isReady}). `true` ⇔ the persisted diff --git a/tests/unit/brainy/maintenance-debt.test.ts b/tests/unit/brainy/maintenance-debt.test.ts new file mode 100644 index 00000000..4026d655 --- /dev/null +++ b/tests/unit/brainy/maintenance-debt.test.ts @@ -0,0 +1,122 @@ +/** + * @module tests/unit/brainy/maintenance-debt + * @description Coverage for `brain.maintenanceDebt()` (8.10.1) — the + * observability seam so an operator sees a provider's outstanding background + * maintenance work (compaction, deferred writes, a build-new→verify→swap in + * flight, ...) BEFORE it grinds a transaction into a budget-busting op, the + * same failure class documented on `TransactionTimeoutError` + * (src/transaction/errors.ts). Sibling to tests/unit/brainy/warm.test.ts, + * which establishes this file's technique: shape the probe points brain.ts + * reads (`typeof provider.maintenanceDebt === 'function'`) directly on the + * REAL, live provider instances rather than hand-rolling full fakes for the + * larger `MetadataIndexProvider` / `GraphIndexProvider` interfaces. + * + * `brain.maintenanceDebt()` is a PURE PASSTHROUGH: no thresholds, no + * polling, no JS-side estimation — these tests pin exactly that by asserting + * the returned payload is the provider's object, verbatim. + */ +import { describe, it, expect } from 'vitest' +import { Brainy } from '../../../src/brainy.js' +import { NounType } from '../../../src/types/graphTypes.js' +import type { ProviderMaintenanceDebt } from '../../../src/plugin.js' + +// Brainy's ValidationConfig fixes vectors at exactly 384 dimensions +// (src/utils/paramValidation.ts) — match it so add() doesn't reject test data. +const DIM = 384 +const V = (seed = 1): number[] => Array.from({ length: DIM }, (_, i) => Math.sin(seed + i)) + +async function freshBrain(): Promise> { + const brain = new Brainy({ + requireSubtype: false, + storage: { type: 'memory' }, + silent: true + }) + await brain.init() + await brain.add({ data: 'a', type: NounType.Thing, vector: V(1) }) + return brain +} + +describe('brain.maintenanceDebt()', () => { + it('reports "unavailable" for every surface when no active provider implements maintenanceDebt() (the built-in JS stack today)', async () => { + const brain = await freshBrain() + + const report = await brain.maintenanceDebt() + + expect(report.vector.outcome).toBe('unavailable') + expect(report.vector.debt).toBeUndefined() + expect(report.metadata.outcome).toBe('unavailable') + expect(report.metadata.debt).toBeUndefined() + expect(report.graph.outcome).toBe('unavailable') + expect(report.graph.debt).toBeUndefined() + + await brain.close() + }) + + it('reports "reported" + the exact payload when the active provider implements maintenanceDebt() (verbatim passthrough, no thresholding)', async () => { + const brain = await freshBrain() + + const vectorDebt: ProviderMaintenanceDebt = { + pendingBytes: 4_096, + pendingItems: 12, + lastPassCompletedAt: 1_700_000_000_000, + lastPassOutcome: 'completed', + converging: true + } + ;(brain as any).index.maintenanceDebt = async () => vectorDebt + + const report = await brain.maintenanceDebt() + + expect(report.vector.outcome).toBe('reported') + // Verbatim passthrough — the exact object, not a re-derived copy. + expect(report.vector.debt).toBe(vectorDebt) + // Untouched surfaces stay honestly 'unavailable'. + expect(report.metadata.outcome).toBe('unavailable') + expect(report.graph.outcome).toBe('unavailable') + + await brain.close() + }) + + it('mixed surfaces: each surface\'s outcome depends ONLY on its OWN active provider — one surface reporting never leaks into another', async () => { + const brain = await freshBrain() + + const metadataDebt: ProviderMaintenanceDebt = { + pendingItems: 3, + lastPassOutcome: 'partial', + converging: false + } + const graphDebt: ProviderMaintenanceDebt = { + pendingBytes: 0, + converging: true + } + ;(brain as any).metadataIndex.maintenanceDebt = async () => metadataDebt + ;(brain as any).graphIndex.maintenanceDebt = async () => graphDebt + // Vector is deliberately left unpatched. + + const report = await brain.maintenanceDebt() + + expect(report.vector.outcome).toBe('unavailable') + expect(report.vector.debt).toBeUndefined() + + expect(report.metadata.outcome).toBe('reported') + expect(report.metadata.debt).toBe(metadataDebt) + + expect(report.graph.outcome).toBe('reported') + expect(report.graph.debt).toBe(graphDebt) + + await brain.close() + }) + + it('an empty ProviderMaintenanceDebt object (every field omitted) is still honestly "reported" — presence of the hook, not the payload\'s richness, drives the outcome', async () => { + const brain = await freshBrain() + + const emptyDebt: ProviderMaintenanceDebt = {} + ;(brain as any).graphIndex.maintenanceDebt = async () => emptyDebt + + const report = await brain.maintenanceDebt() + + expect(report.graph.outcome).toBe('reported') + expect(report.graph.debt).toEqual({}) + + await brain.close() + }) +}) diff --git a/tests/unit/brainy/warm.test.ts b/tests/unit/brainy/warm.test.ts index ce213696..8a0bb4da 100644 --- a/tests/unit/brainy/warm.test.ts +++ b/tests/unit/brainy/warm.test.ts @@ -307,4 +307,92 @@ describe('brain.warm()', () => { expect(report.totalDurationMs).toBeGreaterThanOrEqual(0) await brain.close() }) + + // --- Metadata leg routes through the ACTIVE provider (8.10.1) ----------- + // + // `MetadataIndexProvider` is a ~50-method interface (src/plugin.ts) — far + // too large to hand-write a compliant fake class the way `FakeVectorProvider` + // fakes the ~8-method `VectorIndexProvider` above. Test (c) already + // establishes this file's pattern for the metadata leg: exercise the REAL + // `MetadataIndexManager` instance and shape just the probe points brain.ts + // reads (`typeof provider.warm === 'function'` / + // `typeof provider.hydrateAll === 'function'`) directly on that instance. + // Shadowing an own property on the live object stands in for "a different + // provider implementation" without needing a hand-rolled full fake — the + // rest of the real manager (used by add()/init() above) is untouched. + describe('metadata leg — warm() routes through the active provider', () => { + it('(f) calls the ACTIVE metadata provider\'s warm() when present and reports "warmed", never falling back to hydrateAll', async () => { + const brain = new Brainy({ + requireSubtype: false, + storage: { type: 'memory' }, + silent: true + }) + await brain.init() + await brain.add({ data: 'a', type: NounType.Thing, vector: V(1) }) + + const metadataIndex = (brain as any).metadataIndex + let warmCalls = 0 + let hydrateAllCalls = 0 + const origHydrateAll = metadataIndex.hydrateAll.bind(metadataIndex) + metadataIndex.hydrateAll = async (...args: unknown[]) => { + hydrateAllCalls++ + return origHydrateAll(...args) + } + // Simulates a native metadata provider declaring the optional `warm()` + // hook added to `MetadataIndexProvider` (src/plugin.ts) in 8.10.1. + metadataIndex.warm = async () => { + warmCalls++ + } + + const report = await brain.warm() + + expect(warmCalls).toBe(1) + expect(hydrateAllCalls).toBe(0) // warm() ran — no hydrateAll fallback + expect(report.metadata.outcome).toBe('warmed') + await brain.close() + }) + + it('reports "unavailable" when the active metadata provider implements neither warm() nor hydrateAll() (the honest branch a native provider without either hook must hit)', async () => { + const brain = new Brainy({ + requireSubtype: false, + storage: { type: 'memory' }, + silent: true + }) + await brain.init() + await brain.add({ data: 'a', type: NounType.Thing, vector: V(1) }) + + const metadataIndex = (brain as any).metadataIndex + // Shadow away BOTH optional hooks — models a genuinely native provider + // that (unlike the built-in JS manager) offers neither seam. This must + // never fall back to calling init() as a stand-in for warmth. + metadataIndex.warm = undefined + metadataIndex.hydrateAll = undefined + + const report = await brain.warm() + + expect(report.metadata.outcome).toBe('unavailable') + await brain.close() + }) + + it('the built-in JS manager (no warm()) still reports "warmed" via its existing hydrateAll() duck-type — unchanged by the new provider hook', async () => { + const brain = new Brainy({ + requireSubtype: false, + storage: { type: 'memory' }, + silent: true + }) + await brain.init() + await brain.add({ data: 'a', type: NounType.Thing, vector: V(1) }) + + // No patching at all — the default built-in MetadataIndexManager has + // hydrateAll() but no warm(), exactly as it did before this change. + const metadataIndex = (brain as any).metadataIndex + expect(typeof metadataIndex.warm).not.toBe('function') + expect(typeof metadataIndex.hydrateAll).toBe('function') + + const report = await brain.warm() + + expect(report.metadata.outcome).toBe('warmed') + await brain.close() + }) + }) })