---
document_type: "specification"
service: "MOMENTRY_CORE"
title: "AI-Driven Processor Contract"
date: "2026-03-27"
version: "V1.0"
status: "active"
owner: "Warren"
created_by: "OpenCode"
tags:
  - "ai-processor"
  - "contract"
  - "standardization"
  - "specification"
ai_query_hints:
  - "AI Processor Contract 的規範內容是什麼？"
  - "如何讓自定義 Processor 符合合約標準？"
  - "AI Processor 的標準化介面定義為何？"
---

# AI-Driven Processor Contract

## Overview

This document defines the contract that all AI-driven processors in the Momentry system must follow to ensure consistency, reliability, and maintainability.

## Version

Contract Version: 1.0  
Effective Date: 2025-03-27

## Core Principles

1. **Internal Standardization** – Consistent implementation patterns across all processors
2. **External Communication** – Standardized interfaces for integration with other system components
3. **Self-Monitoring** – Built-in health checks and resource monitoring
4. **Graceful Degradation** – Fallback strategies when optimal processing fails
5. **Performance Awareness** – Adherence to performance constraints (≤5% overhead)

## Command-Line Interface

All processors must support the following command-line arguments:

### Required Arguments
- `video_path` – Path to input video file
- `output_path` – Path where JSON output should be written

### Optional Arguments
- `--uuid`, `-u` – UUID for Redis progress reporting (default: empty string)
- `--check-health` – Perform health check and exit (does not process video)

### Hidden/Configuration Arguments (can also be set via environment variables)
- Processor-specific configuration arguments should be hidden from help (`argparse.SUPPRESS`)
- Environment variable names should follow pattern: `MOMENTRY_{PROCESSOR}_*`

## Redis Progress Reporting

Processors must use the `RedisPublisher` class for progress reporting:

### Message Types
- `info` – General information about processing stages
- `progress` – Percentage completion for long-running tasks
- `warning` – Non-fatal issues that don't stop processing
- `error` – Fatal errors that cause processing to stop
- `complete` – Final completion message with summary statistics

### Message Format
```json
{
  "type": "info|progress|warning|error|complete",
  "processor": "processor_name",
  "message": "Human-readable message",
  "timestamp": "ISO 8601 timestamp"
}
```

## Signal Handling

Processors must handle the following signals:
- `SIGTERM` – Graceful shutdown request from system
- `SIGINT` – User interrupt (Ctrl+C)

Signal handlers should:
1. Log the signal reception
2. Clean up temporary resources
3. Exit with appropriate exit code

## Health Checks

Processors must implement a health check mode (`--check-health`) that:
1. Verifies all required dependencies are available
2. Checks access to required external services (if any)
3. Returns a JSON structure with status and detailed information
4. Exits with code 0 for healthy, non-zero for unhealthy

Example health check output:
```json
{
  "status": "healthy",
  "dependencies": {
    "faster_whisper": "available",
    "psutil": "available"
  },
  "timestamp": "2025-03-27T10:30:00Z"
}
```

## Resource Monitoring

Processors should monitor their own resource usage during long-running operations:
- Sample CPU and memory usage at configurable intervals (default: 60 seconds)
- Log resource usage via Redis publisher when threshold exceeded
- Implement circuit breakers for excessive resource consumption

## Output JSON Schema

All processors must produce JSON output with the following base structure:

### Required Fields
- `processor_name` – String identifying the processor (e.g., "asr", "yolo")
- `processor_version` – Semantic version of the processor implementation
- `contract_version` – Version of this contract (e.g., "1.0")

### Processor-Specific Fields
- Processor-specific data fields (e.g., `segments` for ASR, `frames` for OCR)

### Optional Metadata
- `processing_mode` – How processing was performed (e.g., "direct", "chunked")
- `chunk_count` – Number of chunks used (for chunked processing)
- `chunk_duration` – Duration of each chunk in seconds

### Example ASR Output
```json
{
  "processor_name": "asr",
  "processor_version": "2.0.0",
  "contract_version": "1.0",
  "language": "en",
  "language_probability": 0.95,
  "segments": [
    {
      "start": 0.0,
      "end": 2.5,
      "text": "Hello world"
    }
  ],
  "processing_mode": "chunked",
  "chunk_count": 7,
  "chunk_duration": 600
}
```

## Error Handling

### Graceful Failure
- When processing fails, processors should clean up temporary resources
- Write error information to stderr with clear error messages
- Exit with non-zero exit code

### Fallback Strategies
- Implement fallback processing modes when optimal approach fails (e.g., direct → chunked transcription)
- Document fallback conditions and limitations

## Performance Constraints

### Overhead Limit
- Any optimization or additional functionality must not increase processing time by more than 5%
- Benchmark against baseline implementation to verify compliance

### Timeout Handling
- Respect timeout configurations from system configuration
- Implement progress-based timeout extensions where appropriate

## Checkpointing and Resume (Optional)

For long-running processors (> 5 minutes):
- Implement checkpointing to allow resuming from last saved state
- Save checkpoints at configurable intervals
- Provide mechanism to resume from checkpoint on subsequent runs

## Implementation Checklist

- [ ] Command-line interface compliant with specification
- [ ] Redis progress reporting implemented
- [ ] Signal handlers for SIGTERM and SIGINT
- [ ] Health check mode (`--check-health`)
- [ ] Resource monitoring (optional but recommended)
- [ ] Output JSON includes required base fields
- [ ] Error handling with graceful cleanup
- [ ] Performance overhead within 5% limit
- [ ] Documentation of processor-specific features

## Reference Implementation

The ASR processor (`scripts/asr_processor.py`) serves as the reference implementation for this contract, demonstrating all required and optional features.

## Changelog

### Version 1.0 (2025-03-27)
- Initial contract definition
- Based on ASR processor refactoring experience
