Core Types - rotalabs-comply
Description: AI compliance and audit logging infrastructure

Skip to content

# Core Types

Core data models, enumerations, configuration classes, and exceptions for rotalabs-comply.

## Enumerations

### RiskLevel

Risk severity levels for compliance classification.

These levels are used to categorize the severity of compliance violations and to set risk thresholds for AI systems.

Attributes:

Name | Type | Description
--- | --- | ---
`LOW` |  | Minor risk with minimal compliance impact.
`MEDIUM` |  | Moderate risk requiring attention.
`HIGH` |  | Significant risk requiring immediate action.
`CRITICAL` |  | Severe risk with potential regulatory consequences.

## `LOW = 'low'` `class-attribute` `instance-attribute`

## `MEDIUM = 'medium'` `class-attribute` `instance-attribute`

## `HIGH = 'high'` `class-attribute` `instance-attribute`

## `CRITICAL = 'critical'` `class-attribute` `instance-attribute`

Risk severity levels for compliance classification.

Level | Value | Description
--- | --- | ---
`LOW` | `"low"` | Minor risk with minimal compliance impact
`MEDIUM` | `"medium"` | Moderate risk requiring attention
`HIGH` | `"high"` | Significant risk requiring immediate action
`CRITICAL` | `"critical"` | Severe risk with potential regulatory consequences

Example:

    from rotalabs_comply import RiskLevel

    level = RiskLevel.HIGH
    print(level.value)  # "high"

### Framework

Supported regulatory compliance frameworks.

Each framework represents a set of compliance requirements that can be validated against AI system operations.

Attributes:

Name | Type | Description
--- | --- | ---
`EU_AI_ACT` |  | European Union AI Act requirements.
`SOC2` |  | Service Organization Control 2 security standards.
`HIPAA` |  | Health Insurance Portability and Accountability Act.
`GDPR` |  | General Data Protection Regulation.
`NIST_AI_RMF` |  | NIST AI Risk Management Framework.
`ISO_42001` |  | ISO/IEC 42001 AI Management System standard.

Supported regulatory compliance frameworks.

Framework | Value | Description
--- | --- | ---
`EU_AI_ACT` | `"eu_ai_act"` | European Union AI Act requirements
`SOC2` | `"soc2"` | Service Organization Control 2 standards
`HIPAA` | `"hipaa"` | Health Insurance Portability and Accountability Act
`GDPR` | `"gdpr"` | General Data Protection Regulation
`NIST_AI_RMF` | `"nist_ai_rmf"` | NIST AI Risk Management Framework
`ISO_42001` | `"iso_42001"` | ISO/IEC 42001 AI Management System

Example:

    from rotalabs_comply import Framework

    frameworks = [Framework.EU_AI_ACT, Framework.HIPAA]

## Data Models

### AuditEntry

A single audit log entry capturing an AI system interaction.

This model captures comprehensive information about AI model invocations, including input/output data (or hashes for privacy), safety checks, and performance metrics.

Attributes:

Name | Type | Description
--- | --- | ---
`id` | `str` | Unique identifier for this audit entry (UUID).
`timestamp` | `datetime` | When the interaction occurred.
`provider` | `Optional[str]` | AI provider name (e.g., "openai", "anthropic").
`model` | `Optional[str]` | Model identifier (e.g., "gpt-4", "claude-3-opus").
`conversation_id` | `Optional[str]` | Optional ID linking related interactions.
`input_hash` | `str` | SHA-256 hash of the input content.
`output_hash` | `str` | SHA-256 hash of the output content.
`input_content` | `Optional[str]` | Actual input text (only if store_content enabled).
`output_content` | `Optional[str]` | Actual output text (only if store_content enabled).
`safety_passed` | `bool` | Whether all safety checks passed.
`detectors_triggered` | `List[str]` | List of detector names that flagged content.
`block_reason` | `Optional[str]` | Reason if the interaction was blocked.
`alerts` | `List[str]` | List of alert messages generated.
`latency_ms` | `float` | Response time in milliseconds.
`input_tokens` | `Optional[int]` | Number of input tokens (if available).
`output_tokens` | `Optional[int]` | Number of output tokens (if available).
`metadata` | `Dict[str, Any]` | Additional custom metadata.

Example

> > > entry = AuditEntry( ... provider="openai", ... model="gpt-4", ... input_hash="abc123...", ... output_hash="def456...", ... safety_passed=True, ... detectors_triggered=[], ... latency_ms=245.5, ... )

A single audit log entry capturing an AI system interaction.

Attributes:

Attribute | Type | Description
--- | --- | ---
`id` | `str` | Unique identifier (UUID, auto-generated)
`timestamp` | `datetime` | When the interaction occurred
`provider` | `Optional[str]` | AI provider name (e.g., "openai")
`model` | `Optional[str]` | Model identifier (e.g., "gpt-4")
`conversation_id` | `Optional[str]` | ID linking related interactions
`input_hash` | `str` | SHA-256 hash of input content
`output_hash` | `str` | SHA-256 hash of output content
`input_content` | `Optional[str]` | Actual input (if stored, may be encrypted)
`output_content` | `Optional[str]` | Actual output (if stored, may be encrypted)
`safety_passed` | `bool` | Whether all safety checks passed
`detectors_triggered` | `List[str]` | Safety detectors that flagged content
`block_reason` | `Optional[str]` | Reason if interaction was blocked
`alerts` | `List[str]` | Alert messages generated
`latency_ms` | `float` | Response time in milliseconds
`input_tokens` | `Optional[int]` | Number of input tokens
`output_tokens` | `Optional[int]` | Number of output tokens
`metadata` | `Dict[str, Any]` | Additional custom metadata

Example:

    from rotalabs_comply import AuditEntry

    entry = AuditEntry(
        provider="openai",
        model="gpt-4",
        input_hash="abc123...",
        output_hash="def456...",
        safety_passed=True,
        latency_ms=245.5,
    )

### ComplianceProfile

Configuration profile defining compliance requirements.

This model specifies which regulatory frameworks apply, risk tolerance, documentation requirements, and data handling policies for an AI system.

Attributes:

Name | Type | Description
--- | --- | ---
`frameworks` | `List[Framework]` | List of regulatory frameworks to comply with.
`risk_level` | `RiskLevel` | Maximum acceptable risk level.
`required_documentation` | `bool` | Whether comprehensive docs are required.
`data_retention_days` | `int` | How long to retain audit data.
`encrypt_audit_logs` | `bool` | Whether to encrypt stored audit logs.
`store_content` | `bool` | Whether to store actual content vs just hashes.
`custom_policies` | `Dict[str, Any]` | Additional custom policy configurations.

Example

> > > profile = ComplianceProfile( ... frameworks=[Framework.GDPR, Framework.EU_AI_ACT], ... risk_level=RiskLevel.MEDIUM, ... data_retention_days=365, ... store_content=False, # Privacy mode ... )

Configuration profile defining compliance requirements.

Attributes:

Attribute | Type | Default | Description
--- | --- | --- | ---
`frameworks` | `List[Framework]` | `[]` | Regulatory frameworks to comply with
`risk_level` | `RiskLevel` | `MEDIUM` | Maximum acceptable risk level
`required_documentation` | `bool` | `True` | Whether comprehensive docs required
`data_retention_days` | `int` | `365` | Days to retain audit data
`encrypt_audit_logs` | `bool` | `True` | Whether to encrypt stored logs
`store_content` | `bool` | `False` | Store content vs just hashes
`custom_policies` | `Dict[str, Any]` | `{}` | Custom policy configurations

Example:

    from rotalabs_comply import ComplianceProfile, Framework, RiskLevel

    profile = ComplianceProfile(
        frameworks=[Framework.GDPR, Framework.EU_AI_ACT],
        risk_level=RiskLevel.MEDIUM,
        data_retention_days=365,
        store_content=False,
    )

### ComplianceViolation

A single compliance violation detected during checking.

This model captures details about a specific compliance rule violation, including the framework, severity, and recommended remediation steps.

Attributes:

Name | Type | Description
--- | --- | ---
`framework` | `Framework` | The regulatory framework that was violated.
`rule_id` | `str` | Identifier of the specific rule that was violated.
`severity` | `RiskLevel` | How severe the violation is.
`description` | `str` | Human-readable description of the violation.
`evidence` | `Dict[str, Any]` | Data supporting the violation finding.
`remediation` | `str` | Recommended steps to fix the violation.
`timestamp` | `datetime` | When the violation was detected.

Example

> > > violation = ComplianceViolation( ... framework=Framework.GDPR, ... rule_id="GDPR-ART13-1", ... severity=RiskLevel.HIGH, ... description="Personal data processed without consent record", ... evidence={"field": "user_email", "record_id": "123"}, ... remediation="Implement consent tracking mechanism", ... )

A single compliance violation detected during checking.

Attributes:

Attribute | Type | Description
--- | --- | ---
`framework` | `Framework` | The framework that was violated
`rule_id` | `str` | Identifier of the violated rule
`severity` | `RiskLevel` | Severity of the violation
`description` | `str` | Human-readable description
`evidence` | `Dict[str, Any]` | Data supporting the finding
`remediation` | `str` | Recommended fix steps
`timestamp` | `datetime` | When violation was detected

Example:

    from rotalabs_comply import ComplianceViolation, Framework, RiskLevel

    violation = ComplianceViolation(
        framework=Framework.GDPR,
        rule_id="GDPR-ART13-1",
        severity=RiskLevel.HIGH,
        description="Personal data processed without consent record",
        evidence={"field": "user_email"},
        remediation="Implement consent tracking mechanism",
    )

### ComplianceCheckResult

Result of a compliance check against a regulatory framework.

This model captures the outcome of validating an AI system's operations against compliance requirements, including any violations found.

Attributes:

Name | Type | Description
--- | --- | ---
`passed` | `bool` | Whether the check passed (no critical violations).
`framework` | `Framework` | The framework that was checked against.
`violations` | `List[ComplianceViolation]` | List of compliance violations found.
`warnings` | `List[str]` | Non-critical issues that should be addressed.
`recommendations` | `List[str]` | Suggestions for improving compliance posture.
`checked_at` | `datetime` | When the compliance check was performed.

Example

> > > result = ComplianceCheckResult( ... passed=False, ... framework=Framework.SOC2, ... violations=[violation], ... warnings=["Audit log rotation not configured"], ... recommendations=["Enable encryption for audit logs"], ... )

Result of a compliance check against a regulatory framework.

Attributes:

Attribute | Type | Description
--- | --- | ---
`passed` | `bool` | Whether check passed (no critical violations)
`framework` | `Framework` | Framework checked against
`violations` | `List[ComplianceViolation]` | Violations found
`warnings` | `List[str]` | Non-critical issues
`recommendations` | `List[str]` | Improvement suggestions
`checked_at` | `datetime` | When check was performed

Example:

    from rotalabs_comply import ComplianceCheckResult, Framework

    result = ComplianceCheckResult(
        passed=False,
        framework=Framework.SOC2,
        violations=[violation],
        warnings=["Audit log rotation not configured"],
        recommendations=["Enable encryption for audit logs"],
    )

## Configuration Classes

### AuditConfig

Configuration for audit logging behavior.

This model defines how audit entries are stored, encrypted, rotated, and retained over time.

Attributes:

Name | Type | Description
--- | --- | ---
`destination` | `str` | File path or S3 URL (s3://bucket/prefix) for audit logs.
`encryption_enabled` | `bool` | Whether to encrypt audit log data at rest.
`encryption_key` | `Optional[str]` | Base64-encoded encryption key (auto-generated if not provided).
`retention_days` | `int` | Number of days to retain audit logs before deletion.
`max_file_size_mb` | `int` | Maximum size of a single audit log file before rotation.
`rotation_enabled` | `bool` | Whether to enable automatic log rotation.
`compression_enabled` | `bool` | Whether to compress audit log files.

Example

> > > config = AuditConfig( ... destination="/var/log/ai-audit/", ... encryption_enabled=True, ... retention_days=365, ... rotation_enabled=True, ... )

> > > s3_config = AuditConfig( ... destination="s3://my-bucket/audit-logs/", ... encryption_enabled=True, ... compression_enabled=True, ... )

## `is_s3_destination` `property`

Check if the destination is an S3 URL.

## `s3_bucket` `property`

Extract S3 bucket name from destination if applicable.

## `s3_prefix` `property`

Extract S3 key prefix from destination if applicable.

## `model_post_init(__context)`

Auto-generate encryption key if encryption is enabled but no key provided.

## `validate_destination(v)` `classmethod`

Validate that destination is a valid path or S3 URL.

Configuration for audit logging behavior.

Attributes:

Attribute | Type | Default | Description
--- | --- | --- | ---
`destination` | `str` | Required | File path or S3 URL for logs
`encryption_enabled` | `bool` | `True` | Encrypt data at rest
`encryption_key` | `Optional[str]` | Auto-gen | Base64-encoded encryption key
`retention_days` | `int` | `365` | Days before deletion (1-3650)
`max_file_size_mb` | `int` | `100` | Max file size before rotation
`rotation_enabled` | `bool` | `True` | Enable automatic rotation
`compression_enabled` | `bool` | `False` | Compress audit files

Properties:

Property | Type | Description
--- | --- | ---
`is_s3_destination` | `bool` | Whether destination is S3 URL
`s3_bucket` | `Optional[str]` | S3 bucket name if applicable
`s3_prefix` | `Optional[str]` | S3 key prefix if applicable

Example:

    from rotalabs_comply import AuditConfig

    # File storage
    config = AuditConfig(
        destination="/var/log/ai-audit/",
        encryption_enabled=True,
        retention_days=365,
    )

    # S3 storage
    s3_config = AuditConfig(
        destination="s3://my-bucket/audit-logs/",
        encryption_enabled=True,
        compression_enabled=True,
    )

### StorageConfig

Configuration for storage backend selection and settings.

This model defines which storage backend to use and its specific configuration options.

Attributes:

Name | Type | Description
--- | --- | ---
`backend` | `Literal['file', 's3', 'memory']` | Storage backend type ("file", "s3", or "memory").
`path` | `Optional[str]` | Local file path for file backend.
`bucket` | `Optional[str]` | S3 bucket name for S3 backend.
`prefix` | `Optional[str]` | S3 key prefix for organizing objects.
`region` | `Optional[str]` | AWS region for S3 backend.

Example

> > > file_storage = StorageConfig( ... backend="file", ... path="/var/log/ai-audit/", ... )

> > > s3_storage = StorageConfig( ... backend="s3", ... bucket="my-audit-bucket", ... prefix="prod/audit-logs/", ... region="us-west-2", ... )

> > > memory_storage = StorageConfig( ... backend="memory", # For testing ... )

## `model_post_init(__context)`

Validate backend-specific requirements.

## `validate_bucket(v)` `classmethod`

Validate S3 bucket name.

## `validate_path(v)` `classmethod`

Validate and normalize file path.

Configuration for storage backend selection.

Attributes:

Attribute | Type | Default | Description
--- | --- | --- | ---
`backend` | `Literal["file", "s3", "memory"]` | `"file"` | Storage backend type
`path` | `Optional[str]` | `None` | Local path for file backend
`bucket` | `Optional[str]` | `None` | S3 bucket for S3 backend
`prefix` | `Optional[str]` | `None` | S3 key prefix
`region` | `Optional[str]` | `None` | AWS region for S3

Example:

    from rotalabs_comply import StorageConfig

    # File storage
    file_config = StorageConfig(
        backend="file",
        path="/var/log/ai-audit/",
    )

    # S3 storage
    s3_config = StorageConfig(
        backend="s3",
        bucket="my-audit-bucket",
        prefix="prod/audit-logs/",
        region="us-west-2",
    )

    # Memory storage (testing)
    memory_config = StorageConfig(backend="memory")

## Exceptions

### ComplianceError

Base exception for all compliance-related errors.

All other exceptions in this module inherit from this class, allowing for broad exception catching when needed.

Attributes:

Name | Type | Description
--- | --- | ---
`message` |  | Human-readable error description.
`details` |  | Optional dictionary with additional error context.

## `__init__(message, details=None)`

Initialize a ComplianceError.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`message` | `str` | Human-readable error description. | required
`details` | `Optional[Dict[str, Any]]` | Optional dictionary with additional context about the error. | `None`

## `__str__()`

Return string representation of the error.

Base exception for all compliance-related errors.

Attributes:

Attribute | Type | Description
--- | --- | ---
`message` | `str` | Human-readable error description
`details` | `Dict[str, Any]` | Additional error context

Example:

    from rotalabs_comply import ComplianceError

    try:
        # ... compliance operation
        pass
    except ComplianceError as e:
        print(f"Error: {e.message}")
        print(f"Details: {e.details}")

### AuditError

Exception raised for audit logging failures.

This exception is raised when there are issues with: - Writing audit entries - Reading audit logs - Audit log rotation - Audit data validation

Examples:

    >>> raise AuditError("Failed to write audit entry", {"entry_id": "abc123"})

Exception for audit logging failures.

Raised when: - Writing audit entries fails - Reading audit logs fails - Audit log rotation fails - Audit data validation fails

### StorageError

Exception raised for storage backend failures.

This exception is raised when there are issues with: - Connecting to storage backends (file, S3, etc.) - Reading or writing data to storage - Storage configuration problems - Permission issues

Examples:

    >>> raise StorageError("S3 bucket not accessible", {"bucket": "my-bucket"})

Exception for storage backend failures.

Raised when: - Storage backend connection fails - Reading/writing data fails - Storage configuration is invalid - Permission issues occur

### EncryptionError

Exception raised for encryption/decryption failures.

This exception is raised when there are issues with: - Encrypting audit data - Decrypting stored data - Key management - Invalid encryption configuration

Examples:

    >>> raise EncryptionError("Invalid encryption key format")

Exception for encryption/decryption failures.

Raised when: - Encrypting audit data fails - Decrypting stored data fails - Key management issues occur - Invalid encryption configuration

### ValidationError

Exception raised for data validation failures.

This exception is raised when there are issues with: - Invalid input data format - Missing required fields - Data type mismatches - Schema validation failures

Attributes:

Name | Type | Description
--- | --- | ---
`field` |  | Optional name of the field that failed validation.
`value` |  | Optional value that caused the validation failure.

Examples:

    >>> raise ValidationError(
    ...     "Invalid risk level",
    ...     details={"field": "risk_level", "value": "UNKNOWN"}
    ... )

## `__init__(message, details=None, field=None, value=None)`

Initialize a ValidationError.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`message` | `str` | Human-readable error description. | required
`details` | `Optional[Dict[str, Any]]` | Optional dictionary with additional context. | `None`
`field` | `Optional[str]` | Optional name of the field that failed validation. | `None`
`value` | `Optional[Any]` | Optional value that caused the validation failure. | `None`

Exception for data validation failures.

Additional Attributes:

Attribute | Type | Description
--- | --- | ---
`field` | `Optional[str]` | Field that failed validation
`value` | `Optional[Any]` | Value that caused failure

Example:

    from rotalabs_comply import ValidationError

    try:
        # ... validation
        pass
    except ValidationError as e:
        print(f"Field: {e.field}")
        print(f"Value: {e.value}")

### FrameworkError

Exception raised for regulatory framework-related failures.

This exception is raised when there are issues with: - Unsupported framework operations - Framework rule validation - Framework configuration errors - Incompatible framework combinations

Attributes:

Name | Type | Description
--- | --- | ---
`framework` |  | Optional identifier of the framework that caused the error.

Examples:

    >>> raise FrameworkError(
    ...     "Framework not supported",
    ...     details={"framework": "UNKNOWN_FRAMEWORK"}
    ... )

## `__init__(message, details=None, framework=None)`

Initialize a FrameworkError.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`message` | `str` | Human-readable error description. | required
`details` | `Optional[Dict[str, Any]]` | Optional dictionary with additional context. | `None`
`framework` | `Optional[str]` | Optional identifier of the framework that caused the error. | `None`

Exception for framework-related failures.

Additional Attributes:

Attribute | Type | Description
--- | --- | ---
`framework` | `Optional[str]` | Framework that caused the error

Raised when: - Unsupported framework operations - Framework rule validation fails - Framework configuration errors - Incompatible framework combinations