mirror of
https://github.com/lukaszraczylo/claude-mnemonic.git
synced 2026-06-05 23:03:55 +00:00
5c2685c7b6
* feat(leann-phase2): implement hybrid vector storage and graph-based search
- [x] Add AST-aware code chunking for Go, Python, and TypeScript using tree-sitter
- [x] Implement LEANN-inspired hybrid vector storage with hub detection and selective embedding storage (60-80% savings)
- [x] Add observation relationship graph with CSR format and edge detection (file overlap, semantic similarity, temporal, concept)
- [x] Implement graph-aware search with two-level traversal and relationship-based ranking
- [x] Add auto-tuning system for dynamic hub threshold adjustment based on query performance
- [x] Add comprehensive metrics tracking for vector storage, queries, latency, and graph traversals
- [x] Update configuration system with graph and hybrid storage settings
- [x] Add graph stats and vector metrics endpoints to worker service
- [x] Enhance UI sidebar with advanced metrics display and graph visualization
- [x] Optimize struct field alignment throughout codebase for memory efficiency
- [x] Update documentation with LEANN Phase 2 features and performance benefits
- [x] Add tree-sitter dependency for AST parsing
* fix: add fts5 build tag to CI workflow
Pass build-tags: "fts5" to shared workflow to properly compile
sqlite-vec-go-bindings with SQLite FTS5 support.
This fixes test failures in hybrid vector storage tests that require
CGO and FTS5 build tags.
Requires shared-actions@8f7f235 or later.
* docs: add testing documentation and macOS ARM64 known issue
Document the macOS ARM64 CGO linking issue with sqlite-vec-go-bindings
that prevents hybrid package tests from compiling locally.
Added:
- .github/TESTING.md: Comprehensive testing guide with platform-specific
issues, workarounds, and CI configuration details
- internal/vector/hybrid/README.md: Package-specific documentation
explaining the macOS limitation
- .github/CI_FIX_SUMMARY.md: Technical details of the CI fix
Key points:
- 41 out of 42 packages test successfully on all platforms
- hybrid package tests fail only on macOS ARM64 (local dev issue)
- Linux CI tests pass with proper build-tags: "fts5" configuration
- Production builds and runtime functionality unaffected
This is a known limitation of sqlite-vec-go-bindings on macOS ARM64
and does not impact CI/CD or production deployments.
* fix: add SQLite busy_timeout to prevent database locked errors
Set PRAGMA busy_timeout=5000 (5 seconds) to allow SQLite to retry
when the database is locked instead of failing immediately.
This fixes race conditions when multiple goroutines try to write
simultaneously, particularly in tests where StoreObservation spawns
async cleanup goroutines.
Root cause:
- StoreObservation launches goroutine -> CleanupOldObservations
- Multiple concurrent cleanups caused "database is locked" errors
- Without busy_timeout, SQLite fails immediately on lock contention
Solution:
- Add 5-second busy timeout for automatic retry on lock
- Standard practice for concurrent SQLite usage
- Works with existing WAL mode configuration
Fixes TestObservationStore_CleanupOldObservations in CI.
* docs: complete summary of all CI test fixes
Comprehensive documentation of all fixes applied:
1. Missing build tags (fts5)
2. Database locked errors (busy_timeout)
All 41/42 packages now pass tests. The hybrid package has a known
macOS ARM64 limitation that doesn't affect CI or production.
No functionality was removed - all fixes are additive only.
* fix: add SQLite driver import to hybrid tests for CGO linking
Add blank import of mattn/go-sqlite3 to hybrid test files to ensure
the SQLite driver is linked into the test binary. This provides the
SQLite symbols that sqlite-vec-go-bindings requires.
Root cause:
- hybrid package imports sqlitevec (transitively depends on sqlite-vec CGO)
- Test binary needs SQLite symbols for linking
- sqlitevec tests already had this import, but hybrid tests didn't
- Without the driver import, linker fails with "undefined symbols"
This fix enables hybrid tests to run with -race flag on all platforms.
Before: 41/42 packages pass (hybrid failed to link)
After: 42/42 packages pass ✅
Fixes hybrid test compilation on macOS ARM64, Linux, and Windows.
* docs: remove outdated macOS limitation documentation
The hybrid test linking issue has been fixed by adding the SQLite
driver import. All tests now pass on all platforms including macOS.
Removed:
- internal/vector/hybrid/README.md (documented workaround no longer needed)
- .github/TESTING.md (macOS limitation section obsolete)
All 42/42 packages now test successfully with -race flag.
* docs: final comprehensive summary of all CI fixes
All three issues now resolved:
1. Missing fts5 build tags
2. Database busy_timeout for concurrent writes
3. Missing SQLite driver import in hybrid tests
Result: 42/42 packages pass with -race on all platforms.
Credit to reviewer for identifying the race detector concern.
309 lines
8.3 KiB
Go
309 lines
8.3 KiB
Go
package hybrid
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"sort"
|
|
"time"
|
|
|
|
"github.com/lukaszraczylo/claude-mnemonic/internal/graph"
|
|
"github.com/lukaszraczylo/claude-mnemonic/internal/vector/sqlitevec"
|
|
"github.com/lukaszraczylo/claude-mnemonic/pkg/models"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
// GraphConfig configures graph-aware search
|
|
type GraphConfig struct {
|
|
Enabled bool
|
|
MaxHops int // Maximum graph traversal depth (default: 2)
|
|
BranchFactor int // Number of neighbors to expand per node (default: 5)
|
|
EdgeWeight float64 // Minimum edge weight to follow (default: 0.3)
|
|
}
|
|
|
|
// DefaultGraphConfig returns sensible defaults for graph search
|
|
func DefaultGraphConfig() GraphConfig {
|
|
return GraphConfig{
|
|
Enabled: true,
|
|
MaxHops: 2,
|
|
BranchFactor: 5,
|
|
EdgeWeight: 0.3,
|
|
}
|
|
}
|
|
|
|
// GraphSearchClient wraps hybrid.Client with graph-aware search
|
|
type GraphSearchClient struct {
|
|
*Client
|
|
graph *graph.ObservationGraph
|
|
graphConfig GraphConfig
|
|
}
|
|
|
|
// NewGraphSearchClient creates a graph-enhanced hybrid client
|
|
func NewGraphSearchClient(baseClient *Client, observationGraph *graph.ObservationGraph, cfg GraphConfig) *GraphSearchClient {
|
|
return &GraphSearchClient{
|
|
Client: baseClient,
|
|
graph: observationGraph,
|
|
graphConfig: cfg,
|
|
}
|
|
}
|
|
|
|
// Query performs graph-aware vector search with two-level traversal
|
|
func (g *GraphSearchClient) Query(ctx context.Context, query string, limit int, where map[string]any) ([]sqlitevec.QueryResult, error) {
|
|
if !g.graphConfig.Enabled || g.graph == nil {
|
|
// Fall back to standard hybrid search
|
|
return g.Client.Query(ctx, query, limit, where)
|
|
}
|
|
|
|
startTime := time.Now()
|
|
|
|
// 1. Generate query embedding
|
|
queryEmb, err := g.embedSvc.Embed(query)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("embed query: %w", err)
|
|
}
|
|
|
|
// 2. Search hub nodes (stored embeddings)
|
|
hubResults, err := g.base.Query(ctx, query, limit*2, where)
|
|
if err != nil {
|
|
// Fall back to standard search on error
|
|
log.Warn().Err(err).Msg("Hub search failed, falling back to hybrid search")
|
|
return g.Client.Query(ctx, query, limit, where)
|
|
}
|
|
|
|
// 3. Track hub access
|
|
g.trackAccess(hubResults)
|
|
|
|
// 4. Expand via graph traversal
|
|
expandedIDs := g.expandFromHubs(hubResults, limit*4)
|
|
|
|
// 5. Filter to non-hubs that need recomputation
|
|
nonHubIDs := make([]string, 0)
|
|
for _, id := range expandedIDs {
|
|
if !g.isHub(id) {
|
|
nonHubIDs = append(nonHubIDs, id)
|
|
}
|
|
}
|
|
|
|
// 6. Batch recompute non-hub embeddings
|
|
recomputedResults, err := g.recomputeAndScore(ctx, query, nonHubIDs)
|
|
if err != nil {
|
|
log.Warn().Err(err).Msg("Recomputation failed, using hub results only")
|
|
recomputedResults = nil
|
|
}
|
|
|
|
// 7. Apply graph-based ranking boost
|
|
allResults := g.mergeAndRankWithGraph(hubResults, recomputedResults, queryEmb)
|
|
|
|
// 8. Return top K
|
|
if len(allResults) > limit {
|
|
allResults = allResults[:limit]
|
|
}
|
|
|
|
duration := time.Since(startTime)
|
|
log.Debug().
|
|
Dur("duration_ms", duration).
|
|
Int("hubs", len(hubResults)).
|
|
Int("expanded", len(expandedIDs)).
|
|
Int("recomputed", len(recomputedResults)).
|
|
Int("results", len(allResults)).
|
|
Msg("Graph search completed")
|
|
|
|
return allResults, nil
|
|
}
|
|
|
|
// expandFromHubs traverses graph from hub nodes to find promising candidates
|
|
func (g *GraphSearchClient) expandFromHubs(hubResults []sqlitevec.QueryResult, maxCandidates int) []string {
|
|
if g.graph == nil {
|
|
return nil
|
|
}
|
|
|
|
expanded := make(map[string]float64) // doc_id -> relevance score
|
|
visited := make(map[int64]bool)
|
|
|
|
// Start from top hub results
|
|
for i, result := range hubResults {
|
|
if i >= g.graphConfig.BranchFactor*2 {
|
|
break // Limit starting points
|
|
}
|
|
|
|
// Parse observation ID from doc_id
|
|
obsID := parseObservationID(result.ID)
|
|
if obsID == 0 {
|
|
continue
|
|
}
|
|
|
|
// Mark as visited with high relevance (direct match)
|
|
visited[obsID] = true
|
|
expanded[result.ID] = result.Similarity
|
|
|
|
// Traverse graph from this hub
|
|
g.traverseGraph(obsID, result.Similarity, 0, expanded, visited)
|
|
}
|
|
|
|
// Convert to sorted list
|
|
type candidate struct {
|
|
ID string
|
|
Relevance float64
|
|
}
|
|
|
|
candidates := make([]candidate, 0, len(expanded))
|
|
for id, rel := range expanded {
|
|
candidates = append(candidates, candidate{ID: id, Relevance: rel})
|
|
}
|
|
|
|
// Sort by relevance descending
|
|
sort.Slice(candidates, func(i, j int) bool {
|
|
return candidates[i].Relevance > candidates[j].Relevance
|
|
})
|
|
|
|
// Return top candidates
|
|
if len(candidates) > maxCandidates {
|
|
candidates = candidates[:maxCandidates]
|
|
}
|
|
|
|
result := make([]string, len(candidates))
|
|
for i, c := range candidates {
|
|
result[i] = c.ID
|
|
}
|
|
|
|
return result
|
|
}
|
|
|
|
// traverseGraph performs depth-limited graph traversal
|
|
func (g *GraphSearchClient) traverseGraph(nodeID int64, baseRelevance float64, depth int, expanded map[string]float64, visited map[int64]bool) {
|
|
if depth >= g.graphConfig.MaxHops {
|
|
return // Max depth reached
|
|
}
|
|
|
|
// Get neighbors from graph
|
|
neighbors, weights, err := g.graph.GetNeighbors(nodeID)
|
|
if err != nil {
|
|
return // No neighbors or error
|
|
}
|
|
|
|
// Traverse top neighbors by weight
|
|
type neighborWeight struct {
|
|
ID int64
|
|
Weight float32
|
|
}
|
|
|
|
neighborList := make([]neighborWeight, len(neighbors))
|
|
for i := range neighbors {
|
|
neighborList[i] = neighborWeight{
|
|
ID: neighbors[i],
|
|
Weight: weights[i],
|
|
}
|
|
}
|
|
|
|
// Sort by weight descending
|
|
sort.Slice(neighborList, func(i, j int) bool {
|
|
return neighborList[i].Weight > neighborList[j].Weight
|
|
})
|
|
|
|
// Expand top branch_factor neighbors
|
|
expanded_count := 0
|
|
for _, nw := range neighborList {
|
|
if expanded_count >= g.graphConfig.BranchFactor {
|
|
break
|
|
}
|
|
|
|
// Skip if edge weight too low
|
|
if float64(nw.Weight) < g.graphConfig.EdgeWeight {
|
|
continue
|
|
}
|
|
|
|
// Skip if already visited
|
|
if visited[nw.ID] {
|
|
continue
|
|
}
|
|
visited[nw.ID] = true
|
|
|
|
// Calculate propagated relevance (decays with distance)
|
|
decay := 0.7 // 30% decay per hop
|
|
propagatedRelevance := baseRelevance * float64(nw.Weight) * decay
|
|
|
|
// Add to expanded set
|
|
docID := formatObservationDocID(nw.ID)
|
|
if existing, ok := expanded[docID]; !ok || propagatedRelevance > existing {
|
|
expanded[docID] = propagatedRelevance
|
|
}
|
|
|
|
// Recursively traverse
|
|
g.traverseGraph(nw.ID, propagatedRelevance, depth+1, expanded, visited)
|
|
expanded_count++
|
|
}
|
|
}
|
|
|
|
// mergeAndRankWithGraph combines hub and recomputed results with graph-based ranking
|
|
func (g *GraphSearchClient) mergeAndRankWithGraph(hubResults, recomputedResults []sqlitevec.QueryResult, queryEmb []float32) []sqlitevec.QueryResult {
|
|
// Merge results
|
|
allResults := append(hubResults, recomputedResults...)
|
|
|
|
// Apply graph-based re-ranking
|
|
if g.graph != nil {
|
|
for i := range allResults {
|
|
obsID := parseObservationID(allResults[i].ID)
|
|
if obsID == 0 {
|
|
continue
|
|
}
|
|
|
|
// Boost score based on node degree (hubs are more important)
|
|
node, err := g.graph.GetNode(obsID)
|
|
if err == nil && node.Degree > 0 {
|
|
// Degree boost: up to 10% increase for high-degree nodes
|
|
degreeBoost := 1.0 + (0.1 * float64(node.Degree) / 20.0)
|
|
if degreeBoost > 1.1 {
|
|
degreeBoost = 1.1
|
|
}
|
|
allResults[i].Similarity *= degreeBoost
|
|
}
|
|
}
|
|
}
|
|
|
|
// Sort by adjusted similarity
|
|
sortBySimilarity(allResults)
|
|
|
|
return allResults
|
|
}
|
|
|
|
// parseObservationID extracts observation ID from doc_id
|
|
// Format: "obs-{id}-{field}"
|
|
func parseObservationID(docID string) int64 {
|
|
var obsID int64
|
|
// Ignore error - returns 0 on parse failure, which callers handle
|
|
_, _ = fmt.Sscanf(docID, "obs-%d-", &obsID)
|
|
return obsID
|
|
}
|
|
|
|
// formatObservationDocID creates a doc_id for an observation
|
|
func formatObservationDocID(obsID int64) string {
|
|
return fmt.Sprintf("obs-%d-combined", obsID)
|
|
}
|
|
|
|
// GetGraphStats returns statistics about the observation graph
|
|
func (g *GraphSearchClient) GetGraphStats() graph.GraphStats {
|
|
if g.graph == nil {
|
|
return graph.GraphStats{}
|
|
}
|
|
return g.graph.Stats()
|
|
}
|
|
|
|
// RebuildGraph rebuilds the observation graph from current observations
|
|
// This should be called periodically or when observations change significantly
|
|
func (g *GraphSearchClient) RebuildGraph(ctx context.Context, observations []*models.Observation) error {
|
|
log.Info().Int("observations", len(observations)).Msg("Rebuilding observation graph")
|
|
|
|
newGraph, err := graph.BuildFromObservations(ctx, observations)
|
|
if err != nil {
|
|
return fmt.Errorf("build graph: %w", err)
|
|
}
|
|
|
|
g.graph = newGraph
|
|
|
|
log.Info().
|
|
Int("nodes", newGraph.Stats().NodeCount).
|
|
Int("edges", newGraph.Stats().EdgeCount).
|
|
Msg("Graph rebuilt successfully")
|
|
|
|
return nil
|
|
}
|