patterns
patterns
¶
Pattern detection and application for learning from outcomes.
This module implements the "Close the Learning Loop" evolution: - PatternDetector: Analyzes outcomes to detect recurring patterns - PatternMatcher: Matches patterns to current execution context - PatternApplicator: Generates prompt modifications from patterns
The pattern system enables Marianne to learn from past executions and apply that learning to improve future sheet executions.
Classes¶
PatternType
¶
Bases: Enum
Types of patterns that can be detected from outcomes.
Attributes¶
VALIDATION_FAILURE
class-attribute
instance-attribute
¶
Recurring validation failure pattern (e.g., file not created).
RETRY_SUCCESS
class-attribute
instance-attribute
¶
Pattern where retry succeeds after specific failure.
COMPLETION_MODE
class-attribute
instance-attribute
¶
Pattern where completion mode is effective.
SUCCESS_WITHOUT_RETRY
class-attribute
instance-attribute
¶
Pattern of success without retry (positive pattern).
HIGH_CONFIDENCE
class-attribute
instance-attribute
¶
Pattern with high validation confidence.
LOW_CONFIDENCE
class-attribute
instance-attribute
¶
Pattern with low validation confidence (needs attention).
SEMANTIC_FAILURE
class-attribute
instance-attribute
¶
Pattern detected from semantic failure_reason/failure_category analysis.
These patterns are extracted from the failure_reason and failure_category fields in ValidationResult, providing deeper insight into WHY failures occur. Examples: - 'stale' category appearing frequently (files not modified) - 'file not created' reason appearing across multiple sheets
OUTPUT_PATTERN
class-attribute
instance-attribute
¶
Pattern extracted from stdout/stderr output during execution.
These patterns are detected by analyzing the raw output text for common error signatures, stack traces, and failure indicators. Useful for learning from execution-level failures that may not be captured by validation.
SEMANTIC_INSIGHT
class-attribute
instance-attribute
¶
Pattern generated by LLM-based semantic analysis of sheet completions.
These patterns are produced by the conductor's SemanticAnalyzer, which examines sheet output, validation results, and error history to generate deeper insights about why executions succeed or fail. Unlike statistically detected patterns, semantic insights capture nuanced reasoning about prompt effectiveness, agent behavior, and anti-patterns.
RESOURCE_ANOMALY
class-attribute
instance-attribute
¶
Resource anomaly detected during execution (memory spike, zombie, OOM).
These patterns are produced by the profiler's AnomalyDetector, which runs heuristic checks on each system snapshot. No LLM calls — pure threshold-based detection of memory spikes, runaway processes, zombies, FD exhaustion, and memory pressure.
RESOURCE_CORRELATION
class-attribute
instance-attribute
¶
Learned correlation between resource usage and outcomes.
These patterns are produced by the profiler's CorrelationAnalyzer, which periodically cross-references resource profiles of completed jobs with their outcomes (success/failure, validation results) to identify statistical patterns like high-RSS-predicts-failure.
ExtractedPattern
dataclass
¶
ExtractedPattern(pattern_name, matched_text, line_number, context_before=list(), context_after=list(), confidence=0.8, source='stdout')
A pattern extracted from stdout/stderr output analysis.
Represents a specific error or failure pattern found in execution output, with context about where it appeared and confidence in the detection.
Attributes¶
pattern_name
instance-attribute
¶
Canonical name for this pattern (e.g., 'rate_limit', 'import_error').
context_before
class-attribute
instance-attribute
¶
Lines of context before the match (up to 2 lines).
context_after
class-attribute
instance-attribute
¶
Lines of context after the match (up to 2 lines).
confidence
class-attribute
instance-attribute
¶
Confidence in this pattern detection (0.0-1.0).
source
class-attribute
instance-attribute
¶
Source of the pattern: 'stdout' or 'stderr'.
DetectedPattern
dataclass
¶
DetectedPattern(pattern_type, description, frequency=1, success_rate=0.0, last_seen=(lambda: now(tz=UTC))(), context_tags=list(), evidence=list(), confidence=0.5, applications=0, successes_after_application=0, quarantine_status=None, trust_score=None)
A pattern detected from historical outcomes.
Patterns are learned behaviors that can inform future executions. They include both positive patterns (what works) and negative patterns (what to avoid).
v19 Evolution: Extended with optional quarantine_status and trust_score fields for integration with Pattern Quarantine & Trust Scoring features.
Attributes¶
description
instance-attribute
¶
Human-readable description of what this pattern represents.
frequency
class-attribute
instance-attribute
¶
How often this pattern has been observed.
success_rate
class-attribute
instance-attribute
¶
Rate at which this pattern leads to success (0.0-1.0).
last_seen
class-attribute
instance-attribute
¶
When this pattern was last observed (UTC).
context_tags
class-attribute
instance-attribute
¶
Tags for matching: job types, validation types, error categories.
evidence
class-attribute
instance-attribute
¶
Sheet IDs that contributed to detecting this pattern.
confidence
class-attribute
instance-attribute
¶
Confidence in this pattern (0.0-1.0). Higher = more reliable.
applications
class-attribute
instance-attribute
¶
Number of times this pattern was applied (included in prompts).
successes_after_application
class-attribute
instance-attribute
¶
Number of success_without_retry outcomes when this pattern was applied.
quarantine_status
class-attribute
instance-attribute
¶
Quarantine status from global store.
trust_score
class-attribute
instance-attribute
¶
Trust score (0.0-1.0) from global store. None if not from global store.
effectiveness_rate
property
¶
Compute effectiveness rate from applications and successes.
Returns:
| Type | Description |
|---|---|
float
|
Effectiveness rate (0.0-1.0). Returns 0.4 (slightly below neutral) |
float
|
when applications < 3 to prefer proven patterns over unproven ones. |
float
|
This prevents unproven patterns from being treated equally with |
float
|
patterns that have demonstrated moderate (50%) success. |
effectiveness_weight
property
¶
Compute weight for blending effectiveness into relevance scoring.
Uses gradual ramp-up: full weight only after 5 applications. This prevents new patterns from being over-weighted.
Returns:
| Type | Description |
|---|---|
float
|
Weight (0.0-1.0) based on sample size. |
is_quarantined
property
¶
Check if pattern is in quarantine status.
v19 Evolution: Used for quarantine-aware scoring.
is_validated
property
¶
Check if pattern is in validated status.
v19 Evolution: Used for trust-aware scoring.
Functions¶
to_prompt_guidance
¶
Format this pattern as guidance for prompts.
v19 Evolution: Now includes quarantine/trust context when available.
Returns:
| Type | Description |
|---|---|
str
|
A concise string suitable for injection into prompts. |
Source code in src/marianne/learning/patterns.py
PatternDetector
¶
Detects patterns from historical sheet outcomes.
Analyzes a collection of SheetOutcome objects to identify recurring patterns that can inform future executions.
Initialize the pattern detector.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outcomes
|
list[SheetOutcome]
|
List of historical sheet outcomes to analyze. |
required |
Source code in src/marianne/learning/patterns.py
Functions¶
detect_all
¶
Detect all pattern types from outcomes.
Returns:
| Type | Description |
|---|---|
list[DetectedPattern]
|
List of detected patterns sorted by confidence. |
Source code in src/marianne/learning/patterns.py
calculate_success_rate
staticmethod
¶
Calculate overall success rate from outcomes.
Success is defined as validation_pass_rate == 1.0 (all validations passed). Partial passes (e.g., 0.5) are counted as failures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outcomes
|
list[SheetOutcome]
|
List of sheet outcomes. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Success rate as a float (0.0-1.0). |
Source code in src/marianne/learning/patterns.py
PatternMatcher
¶
Matches detected patterns to execution context.
Given a set of detected patterns and a current execution context, finds patterns that are relevant to the current situation.
Initialize the pattern matcher.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patterns
|
list[DetectedPattern]
|
List of detected patterns to match against. |
required |
Source code in src/marianne/learning/patterns.py
Functions¶
match
¶
Find patterns relevant to the given context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
dict[str, Any]
|
Context dict with job_id, sheet_num, validation_types, etc. |
required |
limit
|
int
|
Maximum number of patterns to return. |
5
|
Returns:
| Type | Description |
|---|---|
list[DetectedPattern]
|
List of matching patterns sorted by relevance. |
Source code in src/marianne/learning/patterns.py
PatternApplicator
¶
Applies patterns to modify prompts for better execution.
Takes matched patterns and generates prompt modifications that incorporate learned insights.
Initialize the pattern applicator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patterns
|
list[DetectedPattern]
|
List of patterns to apply. |
required |
Source code in src/marianne/learning/patterns.py
Functions¶
generate_prompt_section
¶
Generate a prompt section from patterns.
Returns:
| Type | Description |
|---|---|
str
|
Formatted markdown section for prompt injection. |
Source code in src/marianne/learning/patterns.py
get_pattern_descriptions
¶
Get pattern descriptions as a list of strings.
Returns:
| Type | Description |
|---|---|
list[str]
|
List of pattern guidance strings. |
Source code in src/marianne/learning/patterns.py
OutputPatternExtractor
¶
Extracts patterns from stdout/stderr output for learning.
Analyzes execution output to detect common failure patterns, error signatures, and other indicators that can inform future executions. This enables Marianne to learn from the raw output of failed executions, not just validation results.
The extractor uses a dictionary of regex patterns to identify common error types like rate limits, import errors, permission denied, etc.
Initialize the output pattern extractor.
Compiles all regex patterns for efficient matching.
Source code in src/marianne/learning/patterns.py
Functions¶
extract_from_output
¶
Extract patterns from execution output.
Scans the output text for known failure patterns and returns a list of ExtractedPattern objects with context.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output
|
str
|
The stdout or stderr text to analyze. |
required |
source
|
str
|
Source identifier ('stdout' or 'stderr'). |
'stdout'
|
Returns:
| Type | Description |
|---|---|
list[ExtractedPattern]
|
List of extracted patterns found in the output. |
Source code in src/marianne/learning/patterns.py
get_pattern_summary
¶
Get a summary count of pattern types found.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
patterns
|
list[ExtractedPattern]
|
List of extracted patterns. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, int]
|
Dict mapping pattern_name to occurrence count. |