Files
test-glm47/ai_coder_1/subtasks/Decomp-005-09.md
T
2026-02-04 16:54:36 +10:00

21 KiB

Subtask: Data Integrity Verification

Parent Task: Decomp/005 Subtask ID: Decomp-005-09 Dependencies: Decomp-005-01 (Storage Architecture), Decomp-005-04 (Data Replication Engine)

Description

Implement data integrity verification system. Support checksum validation, periodic integrity scans, corruption detection, and automatic repair from replicas.

Requirements

  • Calculate checksums on upload (MD5, SHA-256)
  • Verify checksums on download
  • Periodic integrity scans
  • Detect corrupted data
  • Auto-repair from healthy replicas
  • Report integrity metrics
  • Support multiple checksum algorithms

Technical Specifications

Integrity verification service:

from typing import List, Dict, Any, Optional, Tuple
from dataclasses import dataclass
from datetime import datetime, timezone, timedelta
from enum import Enum
import hashlib
import logging

logger = logging.getLogger(__name__)

class ChecksumAlgorithm(Enum):
    """Supported checksum algorithms."""
    MD5 = "md5"
    SHA1 = "sha1"
    SHA256 = "sha256"
    SHA512 = "sha512"

@dataclass
class ChecksumResult:
    """Result of checksum calculation."""
    algorithm: ChecksumAlgorithm
    checksum: str
    bytes_processed: int

@dataclass
class IntegrityStatus:
    """Integrity status for an object."""
    object_id: int
    bucket_id: int
    object_key: str
    expected_checksum: str
    actual_checksum: str
    is_valid: bool
    nodes_checked: List[str]
    corrupt_nodes: List[str]
    healthy_nodes: List[str]

@dataclass
class ScanResult:
    """Result of an integrity scan."""
    objects_scanned: int
    objects_valid: int
    objects_corrupt: int
    objects_missing_replicas: int
    scan_duration_seconds: float
    errors: List[str]

class IntegrityVerificationService:
    """Service for data integrity verification."""

    def __init__(self, db, storage_adapter):
        self.db = db
        self.storage = storage_adapter

    def calculate_checksum(
        self,
        data: bytes,
        algorithm: ChecksumAlgorithm = ChecksumAlgorithm.MD5
    ) -> ChecksumResult:
        """Calculate checksum for data."""
        if algorithm == ChecksumAlgorithm.MD5:
            checksum = hashlib.md5(data).hexdigest()
        elif algorithm == ChecksumAlgorithm.SHA1:
            checksum = hashlib.sha1(data).hexdigest()
        elif algorithm == ChecksumAlgorithm.SHA256:
            checksum = hashlib.sha256(data).hexdigest()
        elif algorithm == ChecksumAlgorithm.SHA512:
            checksum = hashlib.sha512(data).hexdigest()
        else:
            raise ValueError(f"Unsupported algorithm: {algorithm}")

        return ChecksumResult(
            algorithm=algorithm,
            checksum=checksum,
            bytes_processed=len(data)
        )

    def calculate_checksum_from_file(
        self,
        file_path: str,
        algorithm: ChecksumAlgorithm = ChecksumAlgorithm.MD5
    ) -> ChecksumResult:
        """Calculate checksum for a file (streaming for large files)."""
        hash_func = None
        if algorithm == ChecksumAlgorithm.MD5:
            hash_func = hashlib.md5()
        elif algorithm == ChecksumAlgorithm.SHA256:
            hash_func = hashlib.sha256()
        else:
            raise ValueError(f"Unsupported algorithm: {algorithm}")

        with open(file_path, "rb") as f:
            for chunk in iter(lambda: f.read(8192), b""):
                hash_func.update(chunk)

        return ChecksumResult(
            algorithm=algorithm,
            checksum=hash_func.hexdigest(),
            bytes_processed=file_path.stat().st_size
        )

    async def verify_object_integrity(
        self,
        object_id: int
    ) -> IntegrityStatus:
        """
        Verify integrity of an object across all replicas.

        Reads data from each node and compares checksums.
        """
        async with self.db.acquire() as conn:
            obj = await conn.fetchrow(
                """SELECT o.*, b.name as bucket_name
                   FROM objects o
                   JOIN buckets b ON b.id = o.bucket_id
                   WHERE o.id = $1""",
                object_id
            )

            if not obj:
                raise ValueError(f"Object {object_id} not found")

        expected_etag = obj["etag"]
        storage_nodes = json.loads(obj.get("storage_nodes", "[]"))
        bucket_name = obj["bucket_name"]
        object_key = obj["object_key"]

        # Read and verify from each node
        healthy_nodes = []
        corrupt_nodes = []

        for node_id in storage_nodes:
            try:
                file_path = f"{bucket_name}/{object_key}"
                data = await self.storage.read_file(node_id, file_path)

                # Calculate checksum
                actual_etag = hashlib.md5(data).hexdigest()

                if actual_etag == expected_etag:
                    healthy_nodes.append(node_id)
                else:
                    logger.error(
                        f"Checksum mismatch for object {object_id} "
                        f"on node {node_id}: expected {expected_etag}, got {actual_etag}"
                    )
                    corrupt_nodes.append(node_id)

            except Exception as e:
                logger.error(f"Failed to read object {object_id} from node {node_id}: {e}")
                corrupt_nodes.append(node_id)

        is_valid = len(healthy_nodes) > 0
        # Consider valid if at least one replica is healthy

        # Record verification result
        async with self.db.acquire() as conn:
            await conn.execute(
                """INSERT INTO integrity_checks
                   (object_id, checksum_algorithm, expected_checksum, is_valid,
                    healthy_nodes, corrupt_nodes, checked_at)
                   VALUES ($1, 'md5', $2, $3, $4, $5, NOW())""",
                object_id, expected_etag, is_valid,
                healthy_nodes, corrupt_nodes
            )

        return IntegrityStatus(
            object_id=object_id,
            bucket_id=obj["bucket_id"],
            object_key=object_key,
            expected_checksum=expected_etag,
            actual_checksum=expected_etag if is_valid else "MISMATCH",
            is_valid=is_valid,
            nodes_checked=storage_nodes,
            corrupt_nodes=corrupt_nodes,
            healthy_nodes=healthy_nodes
        )

    async def scan_bucket_integrity(
        self,
        bucket_id: int,
        sample_size: int = 1000,
        repair_corrupted: bool = True
    ) -> ScanResult:
        """
        Scan bucket for integrity issues.

        Args:
            bucket_id: Bucket to scan
            sample_size: Number of objects to check (for large buckets)
            repair_corrupted: Attempt to repair corrupted objects

        Returns:
            ScanResult with statistics
        """
        start_time = datetime.now(timezone.utc)

        objects_scanned = 0
        objects_valid = 0
        objects_corrupt = 0
        objects_missing_replicas = 0
        errors = []

        async with self.db.acquire() as conn:
            # Get sample of objects
            objects = await conn.fetch(
                """SELECT o.id, o.bucket_id, o.object_key, o.storage_nodes, o.etag,
                          COUNT(r.id) as replica_count
                   FROM objects o
                   LEFT JOIN replication_status r ON r.object_id = o.id AND r.status = 'completed'
                   WHERE o.bucket_id = $1
                     AND o.is_delete_marker = FALSE
                   GROUP BY o.id
                   ORDER BY RANDOM()
                   LIMIT $2""",
                bucket_id, sample_size
            )

        for obj in objects:
            objects_scanned += 1

            try:
                status = await self.verify_object_integrity(obj["id"])

                if status.is_valid:
                    objects_valid += 1

                    # Check if we have enough replicas
                    expected_replicas = 3
                    actual_replicas = len(status.healthy_nodes)

                    if actual_replicas < expected_replicas:
                        objects_missing_replicas += 1

                        if repair_corrupted:
                            await self._repair_object(obj["id"], status)
                else:
                    objects_corrupt += 1

                    if repair_corrupted:
                        await self._repair_object(obj["id"], status)

            except Exception as e:
                errors.append(f"{obj['id']}: {str(e)}")
                logger.error(f"Error checking object {obj['id']}: {e}")

        duration = (datetime.now(timezone.utc) - start_time).total_seconds()

        return ScanResult(
            objects_scanned=objects_scanned,
            objects_valid=objects_valid,
            objects_corrupt=objects_corrupt,
            objects_missing_replicas=objects_missing_replicas,
            scan_duration_seconds=duration,
            errors=errors
        )

    async def _repair_object(
        self,
        object_id: int,
        status: IntegrityStatus
    ):
        """
        Repair a corrupted object from healthy replicas.

        Copies data from healthy nodes to corrupt/missing nodes.
        """
        if not status.healthy_nodes:
            logger.error(f"Cannot repair object {object_id}: no healthy replicas")
            return

        source_node = status.healthy_nodes[0]

        # Get object details
        async with self.db.acquire() as conn:
            obj = await conn.fetchrow(
                """SELECT o.*, b.name as bucket_name
                   FROM objects o
                   JOIN buckets b ON b.id = o.bucket_id
                   WHERE o.id = $1""",
                object_id
            )

        # Read from healthy node
        file_path = f"{obj['bucket_name']}/{obj['object_key']}"
        data = await self.storage.read_file(source_node, file_path)

        # Write to corrupt/missing nodes
        repaired = 0

        for node_id in status.corrupt_nodes:
            try:
                await self.storage.write_file(
                    node_id=node_id,
                    bucket_name=obj["bucket_name"],
                    object_key=obj["object_key"],
                    data=data
                )
                repaired += 1
                logger.info(f"Repaired object {object_id} on node {node_id}")

            except Exception as e:
                logger.error(f"Failed to repair object {object_id} on node {node_id}: {e}")

        # Record repair
        async with self.db.acquire() as conn:
            await conn.execute(
                """INSERT INTO integrity_repairs
                   (object_id, corrupt_nodes, repaired_nodes, repaired_at)
                   VALUES ($1, $2, $3, NOW())""",
                object_id, status.corrupt_nodes,
                status.corrupt_nodes[:repaired]  # Simplified
            )

        logger.info(f"Repaired {repaired} replicas for object {object_id}")

    async def get_integrity_metrics(
        self,
        bucket_id: int = None
    ) -> Dict[str, Any]:
        """Get integrity metrics for a bucket or all objects."""
        async with self.db.acquire() as conn:
            query = """
                SELECT
                    COUNT(*) as total_objects,
                    COUNT(*) FILTER (WHERE checksum_sha256 IS NOT NULL) as has_sha256,
                    COUNT(*) FILTER (WHERE etag IS NOT NULL) as has_md5
                FROM objects
            """
            params = []

            if bucket_id:
                query += " WHERE bucket_id = $1"
                params.append(bucket_id)

            stats = await conn.fetchrow(query, *params)

            # Get recent scan results
            scan_query = """
                SELECT
                    COUNT(*) FILTER (WHERE is_valid = TRUE) as valid_checks,
                    COUNT(*) FILTER (WHERE is_valid = FALSE) as invalid_checks,
                    COUNT(*) as total_checks,
                    MAX(checked_at) as last_check
                FROM integrity_checks
            """
            scan_params = []

            if bucket_id:
                scan_query += " WHERE object_id IN (SELECT id FROM objects WHERE bucket_id = $1)"
                scan_params.append(bucket_id)

            scan_stats = await conn.fetchrow(scan_query, *scan_params)

            return {
                "total_objects": stats["total_objects"] or 0,
                "objects_with_sha256": stats["has_sha256"] or 0,
                "objects_with_md5": stats["has_md5"] or 0,
                "total_integrity_checks": scan_stats["total_checks"] or 0,
                "valid_checks": scan_stats["valid_checks"] or 0,
                "invalid_checks": scan_stats["invalid_checks"] or 0,
                "last_check": scan_stats["last_check"].isoformat() if scan_stats["last_check"] else None,
                "integrity_health_percent": round(
                    (scan_stats["valid_checks"] / scan_stats["total_checks"] * 100)
                    if scan_stats["total_checks"] > 0 else 100,
                    2
                )
            }

    async def get_corrupted_objects(
        self,
        bucket_id: int = None,
        limit: int = 100
    ) -> List[IntegrityStatus]:
        """Get list of objects that failed integrity checks."""
        async with self.db.acquire() as conn:
            query = """
                SELECT ic.object_id, o.bucket_id, o.object_key,
                       ic.expected_checksum, ic.is_valid,
                       ic.healthy_nodes, ic.corrupt_nodes
                FROM integrity_checks ic
                JOIN objects o ON o.id = ic.object_id
                WHERE ic.is_valid = FALSE
            """
            params = []

            if bucket_id:
                query += " AND o.bucket_id = $1"
                params.append(bucket_id)

            query += f" ORDER BY ic.checked_at DESC LIMIT {limit}"

            rows = await conn.fetch(query, *params)

            return [
                IntegrityStatus(
                    object_id=r["object_id"],
                    bucket_id=r["bucket_id"],
                    object_key=r["object_key"],
                    expected_checksum=r["expected_checksum"],
                    actual_checksum="CORRUPT",
                    is_valid=False,
                    nodes_checked=json.loads(r.get("healthy_nodes") or "[]"),
                    corrupt_nodes=json.loads(r.get("corrupt_nodes") or "[]"),
                    healthy_nodes=json.loads(r.get("healthy_nodes") or "[]")
                )
                for r in rows
            ]

Database schema extensions:

-- Integrity checks log
CREATE TABLE integrity_checks (
    id BIGSERIAL PRIMARY KEY,
    object_id BIGINT NOT NULL REFERENCES objects(id) ON DELETE CASCADE,
    checksum_algorithm VARCHAR(20) NOT NULL DEFAULT 'md5',
    expected_checksum VARCHAR(200) NOT NULL,
    actual_checksum VARCHAR(200),
    is_valid BOOLEAN NOT NULL,
    healthy_nodes JSONB DEFAULT '[]'::jsonb,
    corrupt_nodes JSONB DEFAULT '[]'::jsonb,
    checked_at TIMESTAMP NOT NULL DEFAULT NOW()
);

CREATE INDEX idx_integrity_checks_object ON integrity_checks(object_id);
CREATE INDEX idx_integrity_checks_valid ON integrity_checks(is_valid, checked_at)
    WHERE is_valid = FALSE;

-- Integrity repairs log
CREATE TABLE integrity_repairs (
    id BIGSERIAL PRIMARY KEY,
    object_id BIGINT NOT NULL REFERENCES objects(id) ON DELETE CASCADE,
    corrupt_nodes JSONB NOT NULL,
    repaired_nodes JSONB NOT NULL,
    repair_method VARCHAR(50) DEFAULT 'replica_copy',
    repaired_at TIMESTAMP NOT NULL DEFAULT NOW(),
    metadata JSONB DEFAULT '{}'::jsonb
);

CREATE INDEX idx_integrity_repairs_object ON integrity_repairs(object_id);

Integrity monitoring API:

from fastapi import APIRouter, HTTPException, Query

router = APIRouter(prefix="/v1/integrity", tags=["integrity"])

@router.get("/metrics")
async def get_integrity_metrics(
    bucket_id: Optional[int] = None
):
    """Get integrity metrics."""
    service = get_integrity_service()
    return await service.get_integrity_metrics(bucket_id)

@router.post("/scan/{bucket_id}")
async def scan_bucket_integrity(
    bucket_id: int,
    sample_size: int = Query(1000, ge=1, le=10000),
    repair_corrupted: bool = True
):
    """Scan a bucket for integrity issues."""
    service = get_integrity_service()

    result = await service.scan_bucket_integrity(
        bucket_id=bucket_id,
        sample_size=sample_size,
        repair_corrupted=repair_corrupted
    )

    return {
        "bucket_id": bucket_id,
        "scan_result": {
            "objects_scanned": result.objects_scanned,
            "objects_valid": result.objects_valid,
            "objects_corrupt": result.objects_corrupt,
            "objects_missing_replicas": result.objects_missing_replicas,
            "scan_duration_seconds": round(result.scan_duration_seconds, 2),
            "errors": result.errors[:10]  # First 10 errors
        }
    }

@router.get("/objects/{object_id}/integrity")
async def verify_object_integrity(object_id: int):
    """Verify integrity of a specific object."""
    service = get_integrity_service()

    try:
        status = await service.verify_object_integrity(object_id)
        return {
            "object_id": status.object_id,
            "object_key": status.object_key,
            "is_valid": status.is_valid,
            "expected_checksum": status.expected_checksum,
            "nodes_checked": status.nodes_checked,
            "healthy_nodes": status.healthy_nodes,
            "corrupt_nodes": status.corrupt_nodes
        }
    except ValueError as e:
        raise HTTPException(status_code=404, detail=str(e))

@router.get("/corrupted")
async def list_corrupted_objects(
    bucket_id: Optional[int] = None,
    limit: int = Query(100)
):
    """Get list of corrupted objects."""
    service = get_integrity_service()

    corrupted = await service.get_corrupted_objects(bucket_id, limit)

    return {
        "corrupted_objects": [
            {
                "object_id": c.object_id,
                "object_key": c.object_key,
                "bucket_id": c.bucket_id,
                "expected_checksum": c.expected_checksum,
                "healthy_nodes": c.healthy_nodes,
                "corrupt_nodes": c.corrupt_nodes
            }
            for c in corrupted
        ]
    }

Background integrity scanner:

class IntegrityScanner:
    """Background scanner for periodic integrity checks."""

    def __init__(
        self,
        integrity_service: IntegrityVerificationService,
        scan_interval_hours: int = 24
    ):
        self.integrity_service = integrity_service
        self.scan_interval = timedelta(hours=scan_interval_hours)
        self.task: Optional[asyncio.Task] = None

    async def start(self):
        """Start the background scanner."""
        self.task = asyncio.create_task(self._scan_loop())
        logger.info("Integrity scanner started")

    async def stop(self):
        """Stop the background scanner."""
        if self.task:
            self.task.cancel()
            try:
                await self.task
            except asyncio.CancelledError:
                pass

        logger.info("Integrity scanner stopped")

    async def _scan_loop(self):
        """Periodic scan loop."""
        while True:
            try:
                # Get all active buckets
                async with self.integrity_service.db.acquire() as conn:
                    buckets = await conn.fetch(
                        "SELECT id FROM buckets WHERE is_active = TRUE"
                    )

                for bucket in buckets:
                    try:
                        # Scan a sample of each bucket
                        await self.integrity_service.scan_bucket_integrity(
                            bucket_id=bucket["id"],
                            sample_size=1000,  # Sample size per run
                            repair_corrupted=True
                        )
                    except Exception as e:
                        logger.error(f"Error scanning bucket {bucket['id']}: {e}")

                # Wait until next scan
                await asyncio.sleep(self.scan_interval.total_seconds())

            except asyncio.CancelledError:
                break
            except Exception as e:
                logger.error(f"Error in scan loop: {e}")
                await asyncio.sleep(60)  # Wait 1 minute on error

Acceptance Criteria

  • Checksums are calculated on upload
  • Checksums are verified on download
  • Integrity scans detect corruption
  • Corrupted objects are auto-repaired
  • Integrity metrics are tracked
  • Background scanner runs periodically
  • Corrupted objects can be listed

Notes

Trade-offs:

  • Full vs sample scanning: Sample for performance
  • Immediate vs deferred repair: Immediate for data safety

Performance:

  • Parallelize checksum calculations
  • Scan different regions separately

Alternatives considered:

  • ZFS-style end-to-end checksums: Overkill for this system
  • Merkle trees: Too complex for object-level