TRuCAL / components /audit_queue.py
johnaugustine's picture
Upload 53 files
95cc8f6 verified
"""
Asynchronous audit queue for TRuCAL's ethical processing pipeline.
Handles non-blocking processing of ledger entries for auditing and learning.
"""
import queue
import threading
import json
from typing import Dict, Any, Callable, Optional
from pathlib import Path
class AuditQueue:
"""
Thread-safe queue for processing and auditing TRuCAL interactions.
Args:
audit_callback: Optional callback function for custom audit logic
output_dir: Directory to store audit logs (default: 'logs')
"""
def __init__(
self,
audit_callback: Optional[Callable[[Dict[str, Any]], None]] = None,
output_dir: str = 'logs'
):
self.q = queue.Queue()
self.audit_callback = audit_callback
self.output_dir = Path(output_dir)
self.output_dir.mkdir(parents=True, exist_ok=True)
# Start the audit thread
self.audit_thread = threading.Thread(
target=self._process,
daemon=True,
name="AuditProcessor"
)
self.audit_thread.start()
def submit_for_audit(self, ledger_entry: Dict[str, Any]) -> None:
"""
Submit an entry to the audit queue.
Args:
ledger_entry: Dictionary containing interaction data to audit
"""
self.q.put(ledger_entry)
def _process(self) -> None:
"""Main processing loop for the audit thread."""
while True:
try:
entry = self.q.get()
if entry is None: # Shutdown signal
break
self._audit(entry)
except Exception as e:
print(f"Audit processing error: {e}")
finally:
self.q.task_done()
def _audit(self, entry: Dict[str, Any]) -> None:
"""
Process a single audit entry.
Args:
entry: The ledger entry to audit
"""
try:
# Log the entry to a file
self._log_entry(entry)
# Call custom audit logic if provided
if self.audit_callback:
self.audit_callback(entry)
# Basic rights validation
if 'rights' not in entry or not entry['rights']:
print("Warning: No rights asserted in this session.")
# Check for ethical concerns
self._check_ethical_concerns(entry)
except Exception as e:
print(f"Error during audit processing: {e}")
def _log_entry(self, entry: Dict[str, Any]) -> None:
"""Log the entry to a JSONL file."""
try:
log_file = self.output_dir / 'audit_log.jsonl'
with open(log_file, 'a', encoding='utf-8') as f:
json.dump(entry, f, ensure_ascii=False)
f.write('\n')
except Exception as e:
print(f"Error writing to audit log: {e}")
def _check_ethical_concerns(self, entry: Dict[str, Any]) -> None:
"""Check for potential ethical concerns in the entry."""
# Example: Flag if no ethical considerations were made
if not entry.get('ethical_considerations'):
print("Warning: No explicit ethical considerations documented.")
# Example: Check for sensitive topics
sensitive_terms = ['harm', 'bias', 'privacy', 'safety']
entry_str = str(entry).lower()
if any(term in entry_str for term in sensitive_terms):
print("Note: Entry contains potentially sensitive content.")
def shutdown(self) -> None:
"""Gracefully shut down the audit queue."""
self.q.put(None) # Signal the thread to exit
self.audit_thread.join()
# Global instance for easy import
audit_queue = AuditQueue()