Core Types¶
Core data models, enumerations, configuration classes, and exceptions for rotalabs-comply.
Enumerations¶
RiskLevel¶
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. |
Source code in src/rotalabs_comply/core/types.py
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:
Framework¶
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. |
|
MAS |
Monetary Authority of Singapore FEAT principles. |
Source code in src/rotalabs_comply/core/types.py
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:
Data Models¶
AuditEntry¶
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, ... )
Source code in src/rotalabs_comply/core/types.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | |
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¶
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 ... )
Source code in src/rotalabs_comply/core/types.py
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¶
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", ... )
Source code in src/rotalabs_comply/core/types.py
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¶
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"], ... )
Source code in src/rotalabs_comply/core/types.py
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¶
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, ... )
Source code in src/rotalabs_comply/core/config.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | |
s3_bucket
property
¶
Extract S3 bucket name from destination if applicable.
model_post_init ¶
Auto-generate encryption key if encryption is enabled but no key provided.
Source code in src/rotalabs_comply/core/config.py
validate_destination
classmethod
¶
Validate that destination is a valid path or S3 URL.
Source code in src/rotalabs_comply/core/config.py
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¶
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 ... )
Source code in src/rotalabs_comply/core/config.py
126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 | |
validate_path
classmethod
¶
Validate and normalize file path.
validate_bucket
classmethod
¶
Validate S3 bucket name.
Source code in src/rotalabs_comply/core/config.py
model_post_init ¶
Validate backend-specific requirements.
Source code in src/rotalabs_comply/core/config.py
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¶
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. |
Source code in src/rotalabs_comply/core/exceptions.py
__init__ ¶
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
|
Source code in src/rotalabs_comply/core/exceptions.py
__str__ ¶
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¶
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:
Source code in src/rotalabs_comply/core/exceptions.py
Exception for audit logging failures.
Raised when: - Writing audit entries fails - Reading audit logs fails - Audit log rotation fails - Audit data validation fails
StorageError¶
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:
Source code in src/rotalabs_comply/core/exceptions.py
Exception for storage backend failures.
Raised when: - Storage backend connection fails - Reading/writing data fails - Storage configuration is invalid - Permission issues occur
EncryptionError¶
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:
Source code in src/rotalabs_comply/core/exceptions.py
Exception for encryption/decryption failures.
Raised when: - Encrypting audit data fails - Decrypting stored data fails - Key management issues occur - Invalid encryption configuration
ValidationError¶
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"}
... )
Source code in src/rotalabs_comply/core/exceptions.py
__init__ ¶
__init__(
message: str,
details: Optional[Dict[str, Any]] = None,
field: Optional[str] = None,
value: Optional[Any] = None,
) -> 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
|
Source code in src/rotalabs_comply/core/exceptions.py
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¶
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"}
... )
Source code in src/rotalabs_comply/core/exceptions.py
__init__ ¶
__init__(
message: str,
details: Optional[Dict[str, Any]] = None,
framework: Optional[str] = None,
) -> 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
|
Source code in src/rotalabs_comply/core/exceptions.py
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