Commit graph

28 commits

Author SHA1 Message Date
7e75221ae7 **feat(cache): optimize multi-level cache with dynamic read-only and storage-specific tuning**
- Enhanced `CacheManager` for better handling of large datasets, especially in `S3` or remote storage:
  - Added `REMOTE_API` as a supported storage type.
  - Improved cache sizing and batch tuning:
    - Optimized memory usage based on environment (Browser, Node.js, Worker).
    - Increased cache aggressiveness in read-only mode and for large datasets.
    - Adjusted cache parameters dynamically for S3 or remote storage.
  - Introduced `isReadOnly` and `isRemoteStorage` checks to refine tuning logic.
- Added new `cacheConfig` options:
  - `autoTune`, `autoTuneInterval`, and mode-specific settings for read-only optimizations.
  - Batch sizes, eviction thresholds, and TTLs tailored for operating modes.
- Enhanced documentation:
  - Detailed performance-tuning guides and S3 examples in `README.md`.
  - Included new configuration examples for large datasets in cloud storage.
- Improved extensibility:
  - Unified cache and batch logic under storage type and mode-aware rules.
  - Updated interfaces (`BrainyData`, `StorageFactory`) to include new cache settings.
- Verified enhancements with rigorous testing across multiple configurations.

**Purpose**: Improve caching strategy and query performance in complex cloud and on-premise environments with flexible, dynamic tuning.
2025-08-01 08:50:53 -07:00
f86295eab8 **feat(search): enhance JSON document search with field-level filtering and prioritization**
- Added support for field-specific and prioritized searches in `brainyData`:
  - Introduced `searchField` option to enable targeted field-level searches.
  - Implemented `priorityFields` option for weighted vectorization and query relevance.
- Developed utilities in `jsonProcessing.ts` and `fieldNameTracking.ts`:
  - `extractTextFromJson` for text extraction with customizable depth and field prioritization.
  - `extractFieldFromJson` to target specific fields in JSON documents.
  - `prepareJsonForVectorization` for optimized JSON vectorization.
- Enhanced management of field names and mappings:
  - Integrated `trackFieldNames` to associate fields with their services.
  - Supported cross-service consistency through `standardFieldMappings`.
- Updated documentation:
  - Added detailed guides for JSON search enhancements and HNSW limitations.
  - Extended usage examples in `README.md` and `json-search-test.js`.
- Verified improvements with comprehensive tests:
  - Created unit and integration tests demonstrating search behavior improvements.
  - Addressed previous TypeScript errors related to search parameters.

**Purpose**: Improve search accuracy and usability when working with complex JSON documents by enabling field-specific searches and enhancing contextual relevance.
2025-08-01 08:27:39 -07:00
fa18e73a7f **feat(storage): implement multi-level cache manager with dynamic tuning**
- Added a new `CacheManager` class in `cacheManager.ts` to support three-level caching strategy:
  - **Level 1**: Hot cache in RAM for most accessed nodes.
  - **Level 2**: Warm cache using OPFS, Filesystem, or S3, depending on the environment.
  - **Level 3**: Cold storage for longer-term data storage.
- Integrated features for dynamic tuning:
  - Auto-detection of environment (Browser, Node.js, Worker) and memory availability.
  - Parameter tuning for cache size, eviction thresholds, and TTL based on usage patterns.
- Enhanced support for:
  - LRU-based eviction in hot cache.
  - Batch-based operations with configurable batch sizes.
  - Comprehensive logging and debug outputs for cache operations.
- Ensured robust fallback handling to manage storage in constrained environments.
- Improved extensibility for storage adapters (warm and cold storage detection and initialization).

**Purpose**: Optimize data access and storage across multiple environments with seamless scalability and dynamic parameter adjustments.
2025-07-31 17:57:14 -07:00
1a502def11 **fix(storage): improve restoration and deletion logic in storage adapter**
- Updated `storage-adapter-coverage.test` to handle different adapter behaviors:
  - Memory adapter: size remains 0 after restoration.
  - FileSystem adapter: size matches restored items.
- Enhanced `delete` method in `brainyData.ts`:
  - Added handling for content text passed instead of ID.
  - Improved logging for better traceability during deletions.
- Modified restoration logic to skip index rebuilding during test scenarios:
  - Clears index explicitly in test environments when performing a backup restoration for storage tests.
- Refined logic in `specialized-scenarios.test`:
  - Validated database size changes after adding and deleting items.
  - Enhanced clarity and debugging
2025-07-31 14:03:51 -07:00
c3c4ca31e1 **feat(storage): add pagination and filtering support for nouns and verbs**
- Introduced `PaginationOptions`, `NounFilterOptions`, and `VerbFilterOptions` types for improved query flexibility in data retrieval operations.
- Added `getNouns` and `getVerbs` methods with pagination and filtering capabilities, replacing existing methods for broader use cases and scalability.
- Marked legacy methods (`getAllNouns`, `getAllVerbs`, `getVerbsBySource`, `getVerbsByTarget`, `getVerbsByType`) as deprecated, directing users to use new methods.
- Updated `coreTypes`, `memoryStorage`, and related modules to support new functionality, including cursor and offset-based pagination handling.
- Updated fallback logic for storage adapters, ensuring compatibility with non-paginated operations when required.

**Purpose**: Enhance scalability and query precision by implementing paginated and filtered retrieval of nouns and verbs, aligning query methods with modern requirements.
2025-07-31 13:13:15 -07:00
5d82db12e2 **feat: add write-only mode support and example usage**
- Introduced `writeOnly` mode in `BrainyData` allowing optimized data ingestion by skipping index loading and disabling search operations.
- Enhanced `BrainyDataConfig` to include `writeOnly` support and validate compatibility with `readOnly` mode.
- Implemented error handling for search attempts during `writeOnly` mode.
- Updated the README with detailed usage examples for database modes, including `writeOnly` and `readOnly`.
- Added `examples/write-only-mode.js` to demonstrate practical applications of the `writeOnly` mode.

**Purpose**: Optimize memory usage and startup time for data ingestion scenarios by enabling write-only mode with comprehensive documentation and examples.
2025-07-30 13:32:30 -07:00
e8127c54a5 **feat: implement robust error-handling and operation utilities for storage adapters**
- Added `BrainyError` class to classify and handle errors with types like `TIMEOUT`, `NETWORK`, `STORAGE`, `NOT_FOUND`, and `RETRY_EXHAUSTED`. Includes static helper methods for error creation and retry determination.
- Introduced `operationUtils` with utility functions for timeout, retry logic, and exponential backoff. Implements features like `withTimeout`, `withRetry`, and a combined `withTimeoutAndRetry`.
- Updated `S3CompatibleStorage` to leverage new operation utilities for timeout and retry handling, including `StorageOperationExecutors` for clean operation execution.
- Enhanced `storageFactory` to pass `OperationConfig` for configurable timeout and retry behavior.
- Extended `BrainyData` to include timeout and retry policy configuration at initialization.

**Purpose**: Improve storage reliability by introducing configurable and reusable error-handling and operation utilities, reducing code duplication and enhancing maintainability.
2025-07-30 11:35:09 -07:00
116d6cea79 **docs: add detailed concurrency analysis and implementation documentation**
- Introduced `CONCURRENCY_ANALYSIS.md` to outline identified concurrency issues, including statistics handling, index synchronization, and storage contention.
- Added `CONCURRENCY_IMPLEMENTATION_SUMMARY.md` to summarize concurrency improvements, such as distributed locking and change log mechanisms.
- Created `STORAGE_CONCURRENCY_ANALYSIS.md` to evaluate concurrency risks and applied solutions for different storage adapters (`S3CompatibleStorage`, `FileSystemStorage`, `OPFSStorage`, and `MemoryStorage`).
- Updated codebase with changes related to concurrency, including distributed locking, atomic updates, event-driven synchronization, and change log support.
- Refactored tests to verify behavior of new concurrency mechanisms, including robust error handling and cleanup functions.

**Purpose**: Provides comprehensive documentation and implementation details to ensure robust concurrency handling in multi-instance, high-throughput environments.
2025-07-30 11:01:24 -07:00
524be5010b No commit message can be generated for the provided diff as it appears to be incomplete. Please provide a more descriptive or complete diff to enable me to generate a relevant commit message for you. 2025-07-28 16:25:11 -07:00
94c88e128c **docs: remove outdated statistics-related documentation and add standards**
- **Removed Files**:
  - Deleted outdated statistics documentation files (`statistics.md`, `statistics-flush-solution.md`, `statistics-summary.md`) to clean up the repository and avoid confusion.

- **Added Standards**:
  - Introduced `DOCUMENTATION_STANDARDS.md` to outline naming conventions and troubleshooting practices for more consistent and maintainable project documentation.

- **Tests**:
  - Added a new test file `edge-cases.test.ts` to verify handling of edge cases, ensuring robust behavior against boundary values and invalid inputs.

**Purpose**: Cleans up deprecated documentation while introducing concrete standards for maintaining and updating documentation. Enhances test coverage for unusual or boundary inputs, improving overall system resilience.
2025-07-28 16:00:05 -07:00
86fb1220b6 **feat(core, migration, docs): introduce dimension mismatch resolution tools and migration guide**
- **Core**:
  - Added `check-database.js` to verify database status and validate search functionality.
  - Created `fix-dimension-mismatch.js` to handle re-embedding of existing data to resolve dimension mismatch from 3 to 512.
  - Improved test cases by updating vector operations to support 512 dimensions, replacing previously hardcoded dimensions.

- **Migration**:
  - Developed `DIMENSION_MISMATCH_SUMMARY.md`, detailing the root cause, solution, and preventive strategies for dimension mismatch issues.
  - Added `production-migration-guide.md` for structured production migration with detailed steps on re-embedding strategies, batching, and error handling.

- **Tests**:
  - Enhanced test coverage with 512-dimensional vector validation.
  - Introduced helper functions for consistent vector testing behavior and streamlined search test cases.

- **Documentation**:
  - Updated project documentation to highlight the resolution process for dimension mismatches, emphasizing preventive mechanisms such as auto-migration and version tracking.

**Purpose**: Address critical dimension mismatch issues caused by embedding changes, restore functionality, and provide a roadmap for robust prevention strategies and migration processes.
2025-07-25 13:38:56 -07:00
b81129276c **feat(examples, core, docs): add flushStatistics example, implementation, and documentation**
- **Examples**: Added a new `flush-statistics-example.js` script to demonstrate the usage of the `flushStatistics` method for ensuring updated statistics after data insertion.
- **Core**:
  - Implemented `flushStatistics` in the `BrainyData` class to allow immediate flushing of statistics to storage.
  - Updated `BaseStorageAdapter` with `flushStatisticsToStorage` to support flushing cached statistics.
  - Modified the `shutDown` method to ensure statistics are flushed before database shutdown.
- **Documentation**: Added `statistics-flush-solution.md` to explain the batch update mechanism, the issue with delayed statistics updates, and how to manually flush statistics in storage.

**Purpose**: Provide users with the ability to manually flush statistics for real-time accuracy, particularly useful for systems relying on immediate updates. Improved documentation and examples to guide developers in implementing and using this functionality effectively.
2025-07-25 10:55:37 -07:00
501244398e **feat(core, storage, tests): enhance verb construction with timestamps and metadata**
- **Core**: Improved verb creation logic by adding `createdAt`, `updatedAt`, and `createdBy` attributes. These fields include timestamped metadata (`seconds`, `nanoseconds`) and source augmentation/service information for better tracking.
- **Storage**: Refactored `BaseStorage` methods to utilize internal variants (e.g., `saveVerb_internal`, `getNoun_internal`). Added support for new verb attributes while maintaining backward compatibility with existing data structures.
- **Tests**:
  - Updated `s3-storage.test.ts` and `opfs-storage.test.ts` to validate changes in verb attributes such as timestamps and augmentation metadata.
  - Added assertions for `createdAt`, `updatedAt`, and `createdBy` fields in test cases.
- **Cleanup**: Replaced ambiguous type aliases like `Edge` and `HNSWNode` with clearer equivalents (`Verb` and `HNSWNoun_internal`) for consistency across storage adapters.

**Purpose**: Enhance metadata tracking and standardize attribute handling across storage and core modules to ensure accurate and consistent data throughout the system.
2025-07-25 09:44:10 -07:00
ae3560aad3 **refactor(core): remove redundant whitespace and format code**
- **Code Cleanup**: Removed unnecessary trailing whitespaces across `src/brainyData.ts`. Adjusted formatting for inline object spreads to maintain a consistent coding style.
- **Purpose**: Enhance code readability and ensure adherence to formatting standards without altering functionality.
2025-07-24 17:01:04 -07:00
bc480770b5 **feat(core, statistics, storage): enhance service-level statistics tracking and result filtering**
- **Core**: Introduced a `getCurrentAugmentation` method for detecting active augmentation names. Updated metadata handling to include `createdBy`, `createdAt`, and `updatedAt` attributes for improved tracking.
- **Storage**: Added support for service-based statistics tracking with new methods such as `incrementStatistic`, `decrementStatistic`, and `updateHnswIndexSize`. Implemented persistence for statistics in storage adapters.
- **Statistics**: Enhanced `getStatistics` functionality to provide service-specific breakdowns and support filtering by services. Improved noun, verb, and metadata tracking mechanisms.
- **Search**: Added `service` option to filter results during searches for nouns, verbs, and metadata, ensuring accurate service-based query results.
- **Refactor**: Simplified search logic by integrating HNSW index filtering for better performance when retrieving service-specific results.
- **Tests**: Added comprehensive test coverage for service-level statistics and filtering by service.

**Purpose**: Improve service-level data tracking and analytics while enhancing functionality for filtering and maintaining metadata accuracy to support detailed insights for diverse use cases.
2025-07-24 12:07:47 -07:00
2322b53a0c feat(core, tests): add standalone getStatistics function and improve storage configuration
- **Core**: Introduced a new `getStatistics` utility function in `statistics.ts` for fetching database statistics at the root level of the library. Enhanced `BrainyData` methods to ensure metadata includes `id` field and refined statistics calculations, excluding verbs from the noun count.
- **Tests**: Added comprehensive test coverage in `statistics.test.ts` for the new utility function, validating proper error handling, statistics accuracy, and consistent results between instance methods and standalone function.
- **Storage Config**: Enabled dynamic support for AWS S3, Cloudflare R2, and Google Cloud Storage in web service configuration, utilizing environment variables for adapter setup. Addressed a race condition in `FileSystemStorage` initialization by deferring path module imports.

**Purpose**: Enhance database analytics by introducing a reusable `getStatistics` function, improve flexibility in storage configuration, and ensure robust testing for reliability and accuracy.
2025-07-23 16:26:59 -07:00
b8f10ba39a Merge remote-tracking branch 'origin/main' 2025-07-23 12:39:19 -07:00
b348fcc438 **feat(core): add getStatistics method to BrainyData for detailed DB insights**
- **New Method**:
  - Introduced a new `getStatistics` method in `brainyData.ts` to retrieve key database metrics:
    - Counts for nouns, verbs, metadata entries, and HNSW index size.

- **Error Handling**:
  - Added try-catch blocks to ensure robust error management when fetching metadata or logging failures.

- **Purpose**:
  - Enhances observability of the database state, providing valuable insights for diagnostics and monitoring.
2025-07-23 12:39:17 -07:00
97db2daa50 feat(core): enhance addVerb functionality with auto-creation of missing nouns
- Added `autoCreateMissingNouns` and `missingNounMetadata` options to the `addVerb` method in `brainyData.ts`, enabling automatic creation of missing source or target nouns.
- Improved error handling and logging for auto-creation failures, ensuring better feedback during runtime.
- Reformatted existing code for storage options validation to improve readability and maintain consistency.

**Purpose**: Simplify the addition of relationships by automating the process for non-existing nouns and enhance developer experience with better error handling and logging.
2025-07-22 16:01:48 -07:00
e1632523b4 feat(types): extend FileSystemHandle and optimize imports for consistency
- Added `getFile` method to `FileSystemHandle` interface for enhanced TypeScript compatibility with File System Access API.
- Improved maintainability by reformatting and aligning imports in `brainyData.ts`.
- Standardized spacing and indentation across structured comments and interface fields.

Purpose: Improve TypeScript support for file system operations and enhance code readability with consistent formatting and import management.
2025-07-21 12:48:03 -07:00
e7dcedae60 Fix: handle optional loggingConfig in getDefaultEmbeddingFunction initialization 2025-07-18 10:46:05 -07:00
d3e6dbd898 - Add logging configuration to BrainyData for better control over verbose output.
- Refactor embedding functions to support customizable verbosity through new helper methods (`getDefaultEmbeddingFunction`, `getDefaultBatchEmbeddingFunction`).
- Ensure metadata initialization with default values when null during search results.
2025-07-18 10:40:37 -07:00
51892e46b8 **refactor(core): remove verbose logging for Universal Sentence Encoder**
- **Logging Cleanup**:
  - Removed redundant `console.log` statements in `brainyData.ts` and `embedding.ts` related to Universal Sentence Encoder initialization and load function detection.
  - Replaced detailed logs with concise comments to streamline debugging and reduce noisy outputs.

- **Purpose**:
  - Improves code readability, reduces runtime logging noise, and aligns logging verbosity with the project's streamlined debugging practices.
2025-07-17 10:12:15 -07:00
3ec183dab6 **feat(core): enhance vector handling, model loading, and compatibility**
- **Vector Handling Updates**:
  - Added a `dimensions` property to `BrainyDataConfig` for specifying vector dimensions.
  - Introduced validation for vector dimensions during database creation and insertion to ensure consistency.
  - Enhanced error handling and logging for dimension mismatches.

- **Model Loading Improvements**:
  - Implemented retry logic for Universal Sentence Encoder model loading to handle network instability and JSON parsing errors gracefully.
  - Improved logging and debugging support for failures during model initialization and embedding operations.

- **Compatibility Enhancements**:
  - Updated polyfills to support TensorFlow.js compatibility across diverse server environments (Node.js, serverless, etc.).
  - Introduced and refactored global `TextEncoder`/`TextDecoder` definitions for seamless operation in non-browser environments.
  - Simplified TensorFlow.js backend setup with streamlined imports and logging for GPU/WebGL fallback.

- **Purpose**:
  - These updates improve BrainyData's robustness, enforce correct vector usage, and extend compatibility with varied runtime environments. The changes enhance the usability, reliability, and cross-platform readiness of core functionalities.
2025-07-16 13:51:00 -07:00
b4f1f2d1c5 fix(src/brainyData): enforce consistent formatting and improve fallback mechanisms
- Applied consistent formatting improvements, including line breaks, parentheses usage, and object destructuring, to enhance code readability and maintainability.
- Enhanced the fallback mechanism during Universal Sentence Encoder initialization by implementing a retry approach with error handling.
- Refactored `addBatch` processing for both vector and text items to improve clarity and adhere to project coding standards.
- Optimized initialization safeguards with structured retry implementations, ensuring robust error resiliency.

These changes align the codebase with established formatting guidelines and improve the reliability of embedding initialization processes.
2025-06-30 09:39:06 -07:00
bba9a0c219 feat(src/brainyData, src/utils): enhance embedding efficiency with batch processing and initialize safeguards
- Added batch embedding support with `defaultBatchEmbeddingFunction`, leveraging shared model instances for optimized performance.
- Integrated `isInitializing` flag to prevent recursive initialization and ensure smooth concurrent operation handling during `BrainyData` initialization.
- Pre-loaded Universal Sentence Encoder in `BrainyData` to prevent delays during embedding.
- Introduced fallback mechanisms in embedding initialization for better error resiliency and model reusability.
- Updated `addBatch` with support for batchSize and refactored text/vector processing logic for clearer separation and memory management.
- Improved GPU and CPU backend selection in Universal Sentence Encoder for compatibility across environments.
- Enhanced memory management by cleaning tensors after embedding operations.
- Updated README with instructions for batch embedding, threading updates, and GPU/CPU optimizations.
2025-06-27 14:06:59 -07:00
e884c58310 fix(src/brainyData): enforce consistent formatting and improve code readability
Applied consistent formatting adjustments across `src/brainyData.ts`, including line breaks, parentheses, and object destructuring. These changes enhance code readability, maintainability, and alignment with the project's style guidelines without altering functionality.
2025-06-26 10:56:29 -07:00
5a8a6c1ba3 Initial commit 2025-06-24 11:41:30 -07:00