Skip to content

Conversation

@yileicn
Copy link
Member

@yileicn yileicn commented Dec 19, 2025

PR Type

Enhancement


Description

  • Add new GetKnowledgeCollectionConfig method for optimized single config retrieval

  • Implement caching with SharpCache(10) attribute for performance improvement

  • Refactor KnowledgeSettingHelper to use new optimized method

  • Add Rougamo.Fody dependency to support caching functionality


Diagram Walkthrough

flowchart LR
  A["IBotSharpRepository Interface"] -->|"defines new method"| B["GetKnowledgeCollectionConfig"]
  B -->|"implemented in"| C["FileRepository"]
  B -->|"implemented in"| D["MongoRepository"]
  C -->|"uses SharpCache"| E["Performance Optimization"]
  D -->|"uses SharpCache"| E
  F["KnowledgeSettingHelper"] -->|"refactored to use"| B
  G["Rougamo.Fody"] -->|"enables caching"| E
Loading

File Walkthrough

Relevant files
Enhancement
IBotSharpRepository.cs
Add GetKnowledgeCollectionConfig interface method               

src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs

  • Add new abstract method GetKnowledgeCollectionConfig to interface
  • Method accepts collectionName and vectorStroageProvider parameters
  • Returns single VectorCollectionConfig instead of enumerable
+2/-0     
FileRepository.KnowledgeBase.cs
Implement cached GetKnowledgeCollectionConfig in FileRepository

src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.KnowledgeBase.cs

  • Implement GetKnowledgeCollectionConfig method with SharpCache(10)
    attribute
  • Method filters configs by collection name and vector storage provider
  • Returns first matching config or null using FirstOrDefault()
+11/-0   
KnowledgeSettingHelper.cs
Refactor to use optimized GetKnowledgeCollectionConfig method

src/Plugins/BotSharp.Plugin.KnowledgeBase/Helpers/KnowledgeSettingHelper.cs

  • Replace manual config filtering with call to new
    GetKnowledgeCollectionConfig method
  • Simplify null-coalescing logic using inline operators
  • Reduce code complexity from 11 lines to 4 lines for config retrieval
+5/-16   
MongoRepository.KnowledgeBase.cs
Implement cached GetKnowledgeCollectionConfig in MongoRepository

src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.KnowledgeBase.cs

  • Implement GetKnowledgeCollectionConfig method with SharpCache(10)
    attribute
  • Method filters configs by collection name and vector storage provider
  • Returns first matching config or null using FirstOrDefault()
+11/-0   
Dependencies
BotSharp.Plugin.MongoStorage.csproj
Add Rougamo.Fody dependency for caching support                   

src/Plugins/BotSharp.Plugin.MongoStorage/BotSharp.Plugin.MongoStorage.csproj

  • Add Rougamo.Fody package reference to project dependencies
  • Enables AOP-based caching functionality for the repository
+1/-0     

@qodo-code-review
Copy link

qodo-code-review bot commented Dec 19, 2025

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

🔴
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status:
Misspelled identifier: The newly added parameter name vectorStroageProvider is misspelled, reducing clarity and
propagating the typo across implementations and callers.

Referred Code
VectorCollectionConfig GetKnowledgeCollectionConfig(string collectionName, string vectorStroageProvider)
     => throw new NotImplementedException();

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Nullability mismatch: GetKnowledgeCollectionConfig returns configs?.FirstOrDefault() which can be null but the
method signature returns non-nullable VectorCollectionConfig, risking null-related runtime
issues and missing explicit edge-case handling.

Referred Code
[SharpCache(10)]
public VectorCollectionConfig GetKnowledgeCollectionConfig(string collectionName, string vectorStroageProvider)
{
    var configs = GetKnowledgeCollectionConfigs(new VectorCollectionConfigFilter
    {
        CollectionNames = [collectionName],
        VectorStroageProviders = [vectorStroageProvider]
    });
    return configs?.FirstOrDefault();
}

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
Missing input validation: The new call to db.GetKnowledgeCollectionConfig(collectionName,
settings.VectorDb.Provider) does not validate collectionName/provider for empty or invalid
values before using them to query configuration.

Referred Code
var config = db.GetKnowledgeCollectionConfig(collectionName, settings.VectorDb.Provider);

var textEmbeddingConfig = config?.TextEmbedding;
var provider = textEmbeddingConfig?.Provider ?? settings.Default.TextEmbedding.Provider;
var model = textEmbeddingConfig?.Model ?? settings.Default.TextEmbedding.Model;
var dimension = textEmbeddingConfig?.Dimension ?? settings.Default.TextEmbedding.Dimension;

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
No audit logging: The new optimized config read path does not add any audit logging, so whether this
“critical action” requires audit trails cannot be confirmed from the diff alone.

Referred Code
var config = db.GetKnowledgeCollectionConfig(collectionName, settings.VectorDb.Provider);

var textEmbeddingConfig = config?.TextEmbedding;
var provider = textEmbeddingConfig?.Provider ?? settings.Default.TextEmbedding.Provider;
var model = textEmbeddingConfig?.Model ?? settings.Default.TextEmbedding.Model;
var dimension = textEmbeddingConfig?.Dimension ?? settings.Default.TextEmbedding.Dimension;

Learn more about managing compliance generic rules or creating your own custom rules

  • Update
Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review
Copy link

qodo-code-review bot commented Dec 19, 2025

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
Caching implementation risks serving stale data

The PR adds caching to configuration retrieval but fails to include a cache
invalidation strategy for methods that modify the configuration, risking stale
data being served.

Examples:

src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.KnowledgeBase.cs [114-123]
    [SharpCache(10)]
    public VectorCollectionConfig GetKnowledgeCollectionConfig(string collectionName, string vectorStroageProvider)
    {
        var configs = GetKnowledgeCollectionConfigs(new VectorCollectionConfigFilter
        {
            CollectionNames = [collectionName],
            VectorStroageProviders = [vectorStroageProvider]
        });
        return configs?.FirstOrDefault();
    }
src/Plugins/BotSharp.Plugin.MongoStorage/Repository/MongoRepository.KnowledgeBase.cs [119-128]
    [SharpCache(10)]
    public VectorCollectionConfig GetKnowledgeCollectionConfig(string collectionName, string vectorStroageProvider)
    {
        var configs = GetKnowledgeCollectionConfigs(new VectorCollectionConfigFilter
        {
            CollectionNames = [collectionName],
            VectorStroageProviders = [vectorStroageProvider]
        });
        return configs?.FirstOrDefault();
    }

Solution Walkthrough:

Before:

// In FileRepository and MongoRepository
[SharpCache(10)]
public VectorCollectionConfig GetKnowledgeCollectionConfig(string collectionName, ...)
{
    // ... retrieves and caches config
}

public bool AddKnowledgeCollectionConfigs(...)
{
    // Modifies configs, but does NOT invalidate the cache for GetKnowledgeCollectionConfig
}

public bool DeleteKnowledgeCollectionConfig(string collectionName)
{
    // Deletes a config, but does NOT invalidate the cache
}

After:

// In FileRepository and MongoRepository
[SharpCache(10)]
public VectorCollectionConfig GetKnowledgeCollectionConfig(string collectionName, ...)
{
    // ... retrieves and caches config
}

// Using a hypothetical cache invalidation attribute
[CacheInvalidate(nameof(GetKnowledgeCollectionConfig))]
public bool AddKnowledgeCollectionConfigs(...)
{
    // Modifies configs and invalidates the cache
}

[CacheInvalidate(nameof(GetKnowledgeCollectionConfig))]
public bool DeleteKnowledgeCollectionConfig(string collectionName)
{
    // Deletes a config and invalidates the cache
}
Suggestion importance[1-10]: 9

__

Why: The suggestion correctly identifies a critical design flaw where caching is implemented without invalidation, which will lead to serving stale data and cause incorrect application behavior.

High
Possible issue
Fix signature spelling and nullability

In the GetKnowledgeCollectionConfig method signature, correct the typo in the
vectorStroageProvider parameter to vectorStorageProvider and change the return
type to nullable VectorCollectionConfig?.

src/Infrastructure/BotSharp.Abstraction/Repositories/IBotSharpRepository.cs [236-237]

-VectorCollectionConfig GetKnowledgeCollectionConfig(string collectionName, string vectorStroageProvider)
+VectorCollectionConfig? GetKnowledgeCollectionConfig(string collectionName, string vectorStorageProvider)
      => throw new NotImplementedException();
  • Apply / Chat
Suggestion importance[1-10]: 7

__

Why: This suggestion correctly identifies and fixes both a typo in the parameter name vectorStroageProvider and a type safety issue by making the return type nullable, which is crucial as implementations can return null.

Medium
Learned
best practice
Add input guards and nullable return

Return a nullable type and guard against empty/whitespace inputs so callers can
reliably handle "not found" without exceptions and without caching invalid
lookups.

src/Infrastructure/BotSharp.Core/Repository/FileRepository/FileRepository.KnowledgeBase.cs [114-123]

 [SharpCache(10)]
-public VectorCollectionConfig GetKnowledgeCollectionConfig(string collectionName, string vectorStroageProvider)
+public VectorCollectionConfig? GetKnowledgeCollectionConfig(string collectionName, string vectorStroageProvider)
 {
+    if (string.IsNullOrWhiteSpace(collectionName) || string.IsNullOrWhiteSpace(vectorStroageProvider))
+        return null;
+
     var configs = GetKnowledgeCollectionConfigs(new VectorCollectionConfigFilter
     {
         CollectionNames = [collectionName],
         VectorStroageProviders = [vectorStroageProvider]
     });
-    return configs?.FirstOrDefault();
+
+    return configs.FirstOrDefault();
 }
  • Apply / Chat
Suggestion importance[1-10]: 5

__

Why:
Relevant best practice - Improve defensive coding with precise null and state checks to prevent crashes and incorrect behavior.

Low
  • Update

@JackJiang1234
Copy link
Contributor

reviewed

@yileicn yileicn merged commit 3fb4ef1 into SciSharp:master Dec 22, 2025
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants