Skip to main content

Idiomark V2 Error Handling & Fallbacks

Version: 1.0.0 | Last Updated: 2026-02-11 | Status: Active


Executive Summary​

V2 features add complexity and new failure modes. This document defines error handling strategies, fallback behaviors, and recovery procedures to ensure V2 failures never break core V1 functionality.

Key Principle: V2 is additive. V2 failure must never prevent V1 operation.


Error Handling Philosophy​

The Golden Rule​

┌─────────────────────────────────────────────────────────────────────────────┐
│ │
│ V2 FAILURE MUST NEVER BREAK V1 FUNCTIONALITY │
│ │
│ If V2 fails: │
│ 1. Log the error │
│ 2. Fall back to V1 │
│ 3. Continue operation │
│ 4. Report gracefully to user │
│ │
└─────────────────────────────────────────────────────────────────────────────┘

Error Categories​

CategoryDefinitionHandling Strategy
Extraction ErrorsV2 analysis fails during extractionReturn V1-only result
Validation ErrorsV2 data fails schema validationStrip V2, keep V1
API ErrorsLLM provider fails or times outRetry, then fallback to V1
Performance ErrorsV2 exceeds time/memory budgetAbort V2, use V1
Parse ErrorsV2 response cannot be parsedLog, fallback to V1
Prompt ErrorsV2 prompt builder failsUse V1 prompt builder

Architecture​

Fallback Hierarchy​

┌─────────────────────────────────────────────────────────────────────────────┐
│ FALLBACK HIERARCHY │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ TRY: Full V2 Extraction │ │
│ │ │ │
│ │ ┌──────────────────────────────────────────────────────────┐ │ │
│ │ │ Extract V1 + All 6 V2 Dimensions │ │ │
│ │ └──────────────────────────────────────────────────────────┘ │ │
│ │ │ │ │
│ │ │ Error? │ │
│ │ ▼ │ │
│ │ ┌──────────────────────────────────────────────────────────┐ │ │
│ │ │ FALLBACK 1: Partial V2 │ │ │
│ │ │ Extract V1 + Successful V2 Dimensions Only │ │ │
│ │ └──────────────────────────────────────────────────────────┘ │ │
│ │ │ │ │
│ │ │ Still Error? │ │
│ │ ▼ │ │
│ │ ┌──────────────────────────────────────────────────────────┐ │ │
│ │ │ FALLBACK 2: V1 Only │ │ │
│ │ │ Extract V1 personality only │ │ │
│ │ └──────────────────────────────────────────────────────────┘ │ │
│ │ │ │ │
│ │ │ Still Error? │ │
│ │ ▼ │ │
│ │ ┌──────────────────────────────────────────────────────────┐ │ │
│ │ │ FALLBACK 3: Empty Profile │ │ │
│ │ │ Return minimal valid Idiomark file │ │ │
│ │ └──────────────────────────────────────────────────────────┘ │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘

Error Scenarios & Handling​

Scenario 1: LLM API Failure​

Error: LLM provider returns error or times out

async function extractWithFallback(
textSamples: string[],
enableV2: boolean
): Promise<AnalysisResult> {
// Always extract V1 first (baseline)
const v1Result = await this.extractV1(textSamples)

if (!enableV2) {
return v1Result
}

try {
// Attempt V2 extraction
const v2Result = await this.extractV2(textSamples)
return {
...v1Result,
personality_v2: v2Result.personality
}
} catch (error) {
// V2 failed - log and return V1 only
logger.warn('V2 extraction failed, returning V1 only', {
error: error.message,
stack: error.stack
})

return v1Result // Guaranteed to have V1 data
}
}

Scenario 2: Partial V2 Dimension Failure​

Error: Some V2 dimensions succeed, others fail

async function extractV2Parallel(
textSamples: string[]
): Promise<PersonalityV2> {
const results = await Promise.allSettled([
this.extractBigFive(textSamples),
this.extractLinguisticMarkers(textSamples),
this.extractCommunicationStyle(textSamples),
this.extractCognitivePatterns(textSamples),
this.extractEmotionalPatterns(textSamples),
this.extractSocialDynamics(textSamples)
])

const v2: Partial<PersonalityV2> = {}

// Collect only successful extractions
results.forEach((result, index) => {
const dimensionNames = [
'big_five', 'linguistic_markers', 'communication_style',
'cognitive_patterns', 'emotional_patterns', 'social_dynamics'
]

if (result.status === 'fulfilled') {
v2[dimensionNames[index]] = result.value
} else {
logger.warn(`${dimensionNames[index]} extraction failed`, {
error: result.reason.message
})
}
})

// Return partial V2 (caller handles empty case)
return v2 as PersonalityV2
}

Scenario 3: V2 Response Parse Failure​

Error: LLM returns unparseable JSON

async function extractBigFiveSafe(
textSamples: string[]
): Promise<BigFivePersonality | undefined> {
try {
const response = await this.llmCall(BIG_FIVE_PROMPT, textSamples)

// Attempt to parse
const parsed = JSON.parse(response)

// Validate structure
if (!validateBigFive(parsed)) {
throw new Error('Invalid Big Five structure')
}

return parsed
} catch (error) {
logger.error('Big Five extraction failed', {
error: error.message,
responseLength: response?.length
})

// Return undefined - caller will handle missing dimension
return undefined
}
}

Scenario 4: V2 Prompt Builder Failure​

Error: V2 data is malformed or missing required fields

function buildPromptWithFallback(
idiomarkFile: IdiomarkFile,
message: string,
options: PromptOptions
): string {
try {
// Try V2-aware builder
return buildResponsePromptFromIdiomarkFile(idiomarkFile, message, options)
} catch (error) {
logger.warn('V2 prompt builder failed, using V1', {
error: error.message
})

// Fallback to V1-only builder
return buildResponsePrompt(idiomarkFile.personality, message, options)
}
}

Scenario 5: V2 Validation Failure​

Error: V2 data doesn't pass schema validation

function validateAndCleanV2(
personality_v2: PersonalityV2
): PersonalityV2 | undefined {
const cleaned: PersonalityV2 = {}

// Validate each dimension
for (const [key, value] of Object.entries(personality_v2)) {
try {
// Run validator for this dimension
const validator = validators[key as keyof PersonalityV2]

if (validator && validator(value)) {
cleaned[key] = value
} else {
logger.warn(`V2 dimension ${key} failed validation`)
}
} catch (error) {
logger.warn(`V2 dimension ${key} validation error`, {
error: error.message
})
}
}

// Return undefined if no valid dimensions
return Object.keys(cleaned).length > 0 ? cleaned : undefined
}

Recovery Procedures​

For Users​

When V2 extraction fails:

# CLI automatically falls back to V1
$ idiomark extract --twitter --output profile.idiomark.json --experimental

# If V2 fails, you'll see:
# Warning: V2 extraction failed. Falling back to V1 only.
# Check logs for details.

# Result: Valid V1 Idiomark file (no personality_v2 field)

When V2 reading fails:

// Reader automatically handles missing/broken V2 data
const reader = await loadReader('./profile.idiomark.json')

// If V2 is broken, reader.hasV2Data() returns false
// All V1 operations work normally

For Developers​

Handling V2 extraction errors:

const analyzer = new PersonalityAnalyzer({
provider: 'anthropic',
apiKey: process.env.ANTHROPIC_API_KEY,
enableV2: true,
onError: (error, context) => {
// Custom error handler
if (context.phase === 'v2_extraction') {
// Log but don't throw
console.warn('V2 extraction failed:', error.message)
// Will fall back to V1 automatically
}
}
})

Checking V2 availability:

const reader = await loadReader('./profile.idiomark.json')

// Always check before using V2
if (reader.hasV2Data()) {
// Safe to use V2
const bigFive = reader.getV2Dimension('big_five')
console.log('Openness:', bigFive?.openness)
} else {
// Use V1 only
console.log('V1 voice:', reader.getPersonality().voice.primary)
}

Error Monitoring​

Error Metrics to Track​

interface V2ErrorMetrics {
extraction: {
totalAttempts: number
v2Success: number
v2PartialSuccess: number // Some dimensions succeeded
v2Failure: number // All dimensions failed
v1Fallback: number
}

byDimension: {
[dimension: string]: {
attempts: number
success: number
failure: number
avgLatency: number
}
}

byErrorType: {
[errorType: string]: {
count: number
lastOccurrence: Date
commonContexts: string[]
}
}
}

Alerting Thresholds​

MetricWarningCriticalAction
V2 Failure Rate> 10%> 20%Investigate API issues
Single Dimension Failure> 15%> 30%Check dimension-specific issues
V1 Fallback Rate> 5%> 15%Review V2 reliability
Parse Error Rate> 5%> 10%Update prompt parsing

Best Practices​

For Library Authors​

// DO: Always provide V1 fallback
function analyzePersonality(text: string) {
try {
return analyzeWithV2(text)
} catch (error) {
return analyzeWithV1(text) // Guaranteed to work
}
}

// DON'T: Let V2 errors propagate
function analyzePersonality(text: string) {
return analyzeWithV2(text) // May throw!
}

For Application Developers​

// DO: Check V2 availability
const reader = await loadReader(profilePath)
if (reader.hasV2Data()) {
displayBigFive(reader.getV2Dimension('big_five'))
}

// DON'T: Assume V2 exists
const bigFive = reader.getV2Dimension('big_five') // May be undefined!
displayBigFive(bigFive.openness) // Will crash!

For CLI Users​

# DO: Use --experimental flag explicitly
idiomark extract --twitter --experimental

# DON'T: Assume V2 is enabled by default
idiomark extract --twitter # V1 only, guaranteed

Testing Error Scenarios​

Unit Tests​

describe('V2 Error Handling', () => {
it('should fall back to V1 when V2 extraction fails', async () => {
// Mock V2 failure
mockLLMCall.mockRejectedValueOnce(new Error('API Error'))

const result = await analyzer.analyze(samples)

// Should have V1 data
expect(result.personality).toBeDefined()

// Should not have V2 data
expect(result.personality_v2).toBeUndefined()
})

it('should return partial V2 when some dimensions fail', async () => {
// Mock: Big Five succeeds, Communication Style fails
mockLLMCall
.mockResolvedValueOnce({ big_five: { ... } }) // Success
.mockRejectedValueOnce(new Error('Failed')) // Failure

const result = await analyzer.analyze(samples)

// Should have successful dimension
expect(result.personality_v2.big_five).toBeDefined()

// Should not have failed dimension
expect(result.personality_v2.communication_style).toBeUndefined()
})

it('should handle malformed V2 data gracefully', () => {
const badIdiomark = {
personality: { ... },
personality_v2: { big_five: "not an object" } // Invalid
}

const reader = new IdiomarkReader(badIdiomark)

// Should not crash
expect(reader.hasV2Data()).toBe(false)

// V1 should still work
expect(reader.getPersonality()).toBeDefined()
})
})

Integration Tests​

describe('V2 Fallback Integration', () => {
it('should complete extraction even when V2 fails completely', async () => {
// Simulate complete V2 failure
const analyzer = new PersonalityAnalyzer({
enableV2: true,
llmClient: new FailingLLMClient() // Always throws
})

const result = await analyzer.analyze(samples)

// Extraction should complete
expect(result).toBeDefined()

// V1 should be present
expect(result.personality).toBeDefined()

// V2 should be absent
expect(result.personality_v2).toBeUndefined()
})
})

Error Messages​

User-Facing Messages​

const ERROR_MESSAGES = {
V2_EXTRACTION_FAILED: {
title: 'V2 extraction unavailable',
message: 'Personality was extracted using V1 only. Your profile is fully functional.',
suggestion: 'V2 features are experimental. Try again later or use --no-experimental flag.'
},

V2_PARTIAL_SUCCESS: {
title: 'Partial V2 extraction',
message: 'Some V2 dimensions could not be extracted.',
suggestion: 'Your profile includes available V2 data. Missing dimensions were skipped.'
},

V2_INVALID_DATA: {
title: 'V2 data validation failed',
message: 'V2 data in this profile could not be loaded.',
suggestion: 'Re-extract the profile or contact support.'
}
}

Developer-Facing Messages​

logger.error('V2 extraction failed', {
dimension: 'big_five',
error: error.message,
stack: error.stack,
context: {
sampleCount: textSamples.length,
totalWords: textSamples.join(' ').split(' ').length,
llmProvider: 'anthropic',
model: 'claude-3-opus-20240229',
duration: 3500
}
})

Summary​

AspectStrategy
Core PrincipleV2 failure never breaks V1
Primary FallbackV1-only extraction
Secondary FallbackPartial V2 (successful dimensions only)
Tertiary FallbackEmpty valid Idiomark file
Error ReportingLog errors, inform users gracefully
RecoveryRe-extract with different settings

Document Owner: Idiomark Reliability Team Review Cadence: Monthly Last Updated: 2026-02-11