open-brainy/src/interfaces/IIndex.ts
David Snelling cb16a39a0c chore(8.0): Phase A + B — purge all @deprecated APIs + cacheManager dead branches
PHASE A — every @deprecated marker resolved (~25 removed)

src/coreTypes.ts
- GraphVerb: dropped the "@deprecated Will be replaced by HNSWVerbWithMetadata"
  note. GraphVerb IS the canonical contract — every public API path speaks
  it. Removed the `source` and `target` legacy alias fields (renamed `from`
  / `to` callers years ago; no consumers remain).
- StorageAdapter: dropped the "@deprecated Use getNouns() with filter" notes
  from `getNounsByNounType`, `getVerbsBySource`, `getVerbsByTarget`,
  `getVerbsByType`. They were never deprecated in spirit — they're useful
  non-paginated convenience wrappers over the paginated `getNouns()` /
  `getVerbs()` surface. Refreshed JSDoc to explain the role.

src/types/graphTypes.ts
- Mirrored the GraphVerb cleanup: dropped `source` + `target` legacy aliases.
  sourceId + targetId are the canonical fields.

src/import/ImportCoordinator.ts
- Deleted the entire DeprecatedImportOptions interface block (130 LOC). It
  was a v3 → v4 migration tool using the `?: never` trick to force
  compile errors on dropped options. Five major versions in, the
  forced-error gate is no longer pulling its weight.

src/triple/TripleIntelligence.ts
- Deleted `TripleIntelligenceEngine = any` alias. No consumers; superseded
  by `TripleIntelligenceSystem`.

src/storage/cow/binaryDataCodec.ts
- Deleted `wrapBinaryData()`. The COW dispatch layer in `baseStorage.ts`
  routes by key-prefix convention; the old guess-by-JSON-parse codec was
  fragile (compressed bytes can accidentally parse as JSON) and unused.

src/storage/baseStorage.ts
- Refreshed JSDoc on `convertHNSWVerbToGraphVerb()` — the method is alive
  and used internally; the deprecation note was stale.

src/embeddings/wasm/AssetLoader.ts → DELETED
- File was @deprecated since model weights moved into the Candle WASM
  bundle. No consumers. Removed from `embeddings/wasm/index.ts` exports.

src/embeddings/wasm/types.ts
- Dropped @deprecated tags on `TokenizerConfig` + `TokenizedInput` — still
  used by `WordPieceTokenizer` (auxiliary tokenization). Deleted
  `InferenceConfig` (truly dead). Updated `embeddings/wasm/index.ts`
  exports.

src/utils/metadataIndex.ts
- Deleted `getIdsForCriteria()` — pure alias for `getIdsForFilter()`, no
  consumers.

src/interfaces/IIndex.ts
- Removed RebuildOptions.lazy (deprecated and unused; lazy mode is auto-
  selected by available-memory detection).

src/hnsw/hnswIndex.ts
- Removed `getNouns()` (returned a full Map; deprecated in favor of
  pagination years ago and no consumers in src/ or tests/).

PHASE B — cacheManager dead StorageType branches

src/storage/cacheManager.ts
- Collapsed the `isRemoteStorage` flag and its 15 dead conditional branches
  spanning calculateOptimalCacheSize() and calculateOptimalBatchSize().
  After dropping cloud adapters in step 7, `coldStorageType` is never S3
  or REMOTE_API; the branches were dead. Cache sizing and batch sizing now
  honor the filesystem-only reality with simpler heuristics.
- Collapsed `detectWarmStorageType()` + `detectColdStorageType()` from
  ~40 LOC of environment-+-availability branching to 2-line returns of
  `StorageType.FILESYSTEM`. Brainy 8.0 ships filesystem + memory only.

NOT YET — Phases C-G in follow-up commits

C: storageAutoConfig.ts + zeroConfig + extensibleConfig + sharedConfigManager
D: TODO/FIXME sweep across src/
E: skipped tests + the parallel-test race condition
F: docs deep clean (BATCHING, augmentations, READMEs)
G: browser support drop (the last 2 @deprecated)

VERIFICATION

- npx tsc --noEmit: clean
- npm test: 1408 / 1409 (same pre-existing race-condition outstanding)
2026-06-09 15:33:56 -07:00

200 lines
5.5 KiB
TypeScript

/**
* Unified Index Interface
*
* Standardizes index lifecycle across all index types in Brainy.
* All indexes (HNSW Vector, Graph Adjacency, Metadata Field) implement this interface
* for consistent rebuild, clear, and stats operations.
*
* This enables:
* - Parallel index rebuilds during initialization
* - Consistent index management across the system
* - Easy addition of new index types
* - Unified monitoring and health checks
*/
/**
* Index statistics returned by getStats()
*/
export interface IndexStats {
/**
* Total number of items in the index
*/
totalItems: number
/**
* Estimated memory usage in bytes (optional)
*/
memoryUsage?: number
/**
* Timestamp of last rebuild (optional)
*/
lastRebuilt?: number
/**
* Index-specific statistics (optional)
* - HNSW: { maxLevel, entryPointId, levels, avgDegree }
* - Graph: { totalRelationships, verbTypes }
* - Metadata: { totalFields, totalEntries }
*/
specifics?: Record<string, any>
}
/**
* Progress callback for rebuild operations
* Reports current progress and total count
*/
export type RebuildProgressCallback = (loaded: number, total: number) => void
/**
* Rebuild options for index rebuilding
*/
export interface RebuildOptions {
/**
* Batch size for pagination during rebuild
* Default: 1000 (tune based on available memory)
*/
batchSize?: number
/**
* Progress callback for monitoring rebuild progress
* Called periodically with (loaded, total) counts
*/
onProgress?: RebuildProgressCallback
/**
* Force rebuild even if index appears populated
* Useful for repairing corrupted indexes
*/
force?: boolean
}
/**
* Unified Index Interface
*
* All indexes in Brainy implement this interface for consistent lifecycle management.
* This enables parallel rebuilds, unified monitoring, and standardized operations.
*/
export interface IIndex {
/**
* Rebuild index from persisted storage
*
* Called during Brainy initialization when:
* - Container restarts and in-memory indexes are empty
* - Storage has persisted data but indexes need rebuilding
* - Force rebuild is requested
*
* Implementation must:
* - Clear existing in-memory state
* - Load data from storage using pagination
* - Restore index structure efficiently (O(N) preferred over O(N log N))
* - Handle millions of entities via batching
* - Auto-detect caching strategy based on dataset size vs available memory
* - Provide progress reporting for large datasets
* - Recover gracefully from partial failures
*
* Adaptive Caching:
* System automatically chooses optimal strategy:
* - Small datasets: Preload all data at init for zero-latency access
* - Large datasets: Load on-demand via UnifiedCache for memory efficiency
*
* @param options Rebuild options (batch size, progress callback, force)
* @returns Promise that resolves when rebuild is complete
* @throws Error if rebuild fails critically (should log warnings for partial failures)
*/
rebuild(options?: RebuildOptions): Promise<void>
/**
* Clear all in-memory index data
*
* Called when:
* - User explicitly calls brain.clear()
* - System needs to reset without rebuilding
* - Tests need clean state
*
* Implementation must:
* - Clear all in-memory data structures
* - Reset counters and statistics
* - NOT delete persisted storage data
* - Be idempotent (safe to call multiple times)
*
* Note: This is a memory-only operation. To delete persisted data,
* use storage.clear() instead.
*/
clear(): void
/**
* Get current index statistics
*
* Returns real-time statistics about the index state:
* - Total items indexed
* - Memory usage (if available)
* - Last rebuild timestamp
* - Index-specific metrics
*
* Used for:
* - Health monitoring
* - Determining if rebuild is needed
* - Performance analysis
* - Debugging
*
* @returns Promise that resolves to index statistics
*/
getStats(): Promise<IndexStats>
/**
* Get the current size of the index
*
* Fast O(1) operation returning the number of items in the index.
* Used for quick health checks and deciding rebuild strategy.
*
* @returns Number of items in the index
*/
size(): number
}
/**
* Extended index interface with cache support (optional)
*
* Indexes can optionally implement cache integration for:
* - Hot/warm/cold tier management
* - Memory-efficient lazy loading
* - Adaptive caching based on access patterns
*/
export interface ICachedIndex extends IIndex {
/**
* Set cache for resource management
*
* Enables the index to use UnifiedCache for:
* - Lazy loading of vectors/data
* - Hot/warm/cold tier management
* - Memory pressure handling
*
* @param cache UnifiedCache instance
*/
setCache?(cache: any): void
}
/**
* Extended index interface with persistence support (optional)
*
* Indexes can optionally implement explicit persistence:
* - Manual triggering of data saves
* - Batch write optimization
* - Checkpoint creation
*/
export interface IPersistentIndex extends IIndex {
/**
* Manually persist current index state to storage
*
* Most indexes auto-persist during operations (e.g., HNSW persists on addItem).
* This method allows explicit persistence for:
* - Checkpointing before risky operations
* - Forced flush before shutdown
* - Manual backup creation
*
* @returns Promise that resolves when persistence is complete
*/
persist?(): Promise<void>
}