troubleshoot

package
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 1, 2026 License: GPL-3.0 Imports: 11 Imported by: 0

Documentation

Overview

Package troubleshoot provides AI-powered error diagnosis and pattern recognition.

The package analyzes error messages using AI and semantic pattern matching to provide root cause analysis, hypotheses, and remediation suggestions. Error patterns are stored in a vector database for team-wide knowledge sharing and continuous improvement.

Security

The package implements defense-in-depth security:

  • Input validation for all error messages and patterns
  • Confidence score validation (0.0-1.0 range)
  • Multi-tenant isolation via vector store filtering
  • AI response sanitization and JSON parsing validation
  • Pattern metadata validation before storage

Usage

Basic diagnosis example:

svc, err := troubleshoot.NewService(vectorStore, logger, aiClient)
if err != nil {
    log.Fatal(err)
}
diagnosis, err := svc.Diagnose(ctx,
    "panic: runtime error: invalid memory address",
    "occurred during user authentication",
)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Root cause: %s\n", diagnosis.RootCause)
for _, rec := range diagnosis.Recommendations {
    fmt.Printf("- %s\n", rec)
}

Storing error patterns:

pattern := &troubleshoot.Pattern{
    ErrorType:   "NullPointerException",
    Description: "Null pointer access in authentication flow",
    Solution:    "Add nil check before accessing user object",
    Confidence:  0.9,
    Frequency:   5,
}
err := svc.SavePattern(ctx, pattern)
if err != nil {
    log.Fatal(err)
}

Diagnosis Process

The service follows a multi-stage diagnosis process:

1. Pattern Matching - Search vector database for similar error patterns 2. High-Confidence Check - If pattern match >0.8 confidence, return immediately 3. AI Hypothesis Generation - Query AI client for root cause analysis (if configured) 4. Result Synthesis - Combine pattern matches with AI hypotheses 5. Confidence Scoring - Calculate overall diagnosis confidence

Pattern-based diagnosis is always attempted first for speed and cost efficiency. AI diagnosis is only used when patterns don't provide high-confidence matches.

AI Client

The AI client is optional. If not provided during service creation, the service will operate in pattern-only mode. This is useful for:

  • Testing environments
  • Cost-sensitive deployments
  • Offline operation

When AI is available, it enhances diagnosis with:

  • Root cause identification
  • Multiple hypotheses with likelihood scores
  • Step-by-step remediation recommendations

Performance

Current implementation uses semantic search for pattern matching (100-200ms typical). AI diagnosis adds 1-3 seconds depending on the AI provider and model.

Optimization strategies:

  • High-confidence pattern matches bypass AI (10x faster)
  • Pattern search limited to top 5 results
  • AI prompt includes only top 3 patterns
  • Vector search with filters for efficient pattern retrieval

Pattern Storage

Patterns are stored with embeddings for semantic search:

  • Content: "{error_type}: {description}" for embedding
  • Metadata: error_type, description, solution, confidence, frequency, created_at
  • Unique ID: Generated if not provided (pattern_{uuid})
  • Timestamps: Auto-set if not provided
  • Default confidence: 0.5 if not specified

Patterns support incremental learning via frequency tracking.

Package troubleshoot provides AI-powered error diagnosis and pattern recognition.

This package analyzes error messages using AI and known patterns to provide root cause analysis and remediation suggestions. Patterns are stored in a shared database for team-wide knowledge sharing.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrEmptyErrorMessage indicates error message is required
	ErrEmptyErrorMessage = errors.New("error message cannot be empty")

	// ErrInvalidConfidence indicates confidence score out of range
	ErrInvalidConfidence = errors.New("confidence must be between 0.0 and 1.0")
)

Functions

This section is empty.

Types

type AIClient

type AIClient interface {
	Generate(ctx context.Context, prompt string) (string, error)
}

AIClient defines the interface for AI text generation.

type Diagnosis

type Diagnosis struct {
	ErrorMessage    string       `json:"error_message"`
	RootCause       string       `json:"root_cause"`
	Hypotheses      []Hypothesis `json:"hypotheses"`
	Recommendations []string     `json:"recommendations"`
	RelatedPatterns []Pattern    `json:"related_patterns"`
	Confidence      float64      `json:"confidence"`
}

Diagnosis represents AI-powered error analysis.

type Hypothesis

type Hypothesis struct {
	Description string  `json:"description"`
	Likelihood  float64 `json:"likelihood"`
	Evidence    string  `json:"evidence"`
}

Hypothesis represents a possible cause of the error.

func (*Hypothesis) Validate

func (h *Hypothesis) Validate() error

Validate validates a hypothesis.

type Pattern

type Pattern struct {
	ID          string    `json:"id"`
	ErrorType   string    `json:"error_type"`
	Description string    `json:"description"`
	Solution    string    `json:"solution"`
	Frequency   int       `json:"frequency"`
	Confidence  float64   `json:"confidence"`
	CreatedAt   time.Time `json:"created_at"`
}

Pattern represents a known error pattern with solution.

func (*Pattern) Validate

func (p *Pattern) Validate() error

Validate validates a pattern.

type Service

type Service struct {
	// contains filtered or unexported fields
}

Service provides AI-powered error diagnosis.

func NewService

func NewService(store VectorStore, logger *zap.Logger, aiClient AIClient) (*Service, error)

NewService creates a new troubleshoot service.

The service uses vector storage for pattern matching and an optional AI client for hypothesis generation. If aiClient is nil, the service will only use pattern-based diagnosis.

func (*Service) Diagnose

func (s *Service) Diagnose(ctx context.Context, errorMsg, errorContext string) (*Diagnosis, error)

Diagnose analyzes an error message and provides diagnosis.

The diagnosis process: 1. Search known patterns for similar errors 2. If high-confidence match (>0.8) found, return pattern-based diagnosis 3. Otherwise, query AI for hypothesis generation 4. Combine pattern matches with AI hypotheses 5. Generate recommendations

func (*Service) GetPatterns

func (s *Service) GetPatterns(ctx context.Context) ([]Pattern, error)

GetPatterns retrieves all known error patterns.

Patterns are sorted by frequency (most common first) and returned with their metadata.

func (*Service) SavePattern

func (s *Service) SavePattern(ctx context.Context, pattern *Pattern) error

SavePattern stores an error pattern for future matching.

Patterns are stored in the shared database with embeddings for semantic search. The pattern is validated before storage.

type VectorStore

type VectorStore interface {
	AddDocuments(ctx context.Context, docs []vectorstore.Document) error
	SearchWithFilters(ctx context.Context, query string, k int, filters map[string]interface{}) ([]vectorstore.SearchResult, error)
}

VectorStore defines the interface for vector database operations.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL