# /etc/logrotate.d/hyperstition-sqlite-meta
# Quiescent size-based compression & truncation for the hyperstitionstud.io SQLite REST/MCP API metadata DB.
#
# Why quiescent snapshot compression + in-place SQLite truncation is used:
#   Raw byte truncation (`copytruncate`) on a live SQLite `.db` or `-wal` file while readers or
#   writers hold locks corrupts the SQLite B-tree page header and WAL frame index.
#   Instead, `prerotate` invokes `hyperstitionstud_io.db.sqlite_meta --truncate-quiescent --compress-archive`, which:
#     1. Sets `PRAGMA busy_timeout = 30000` (waits up to 30s for in-flight requests to finish),
#     2. Acquires `BEGIN EXCLUSIVE` to guarantee 100% SQLite reader/writer quiescence,
#     3. Writes a consistent point-in-time SQLite snapshot and compresses it with `gzip -9`
#        to `<db_path>.1.gz` (rotating `.1.gz` .. `.12.gz` rather than removing history),
#     4. Purges the live telemetry tables and commits cleanly,
#     5. Executes `PRAGMA wal_checkpoint(TRUNCATE)` + `VACUUM` + `PRAGMA optimize` on the live DB, and
#     6. Verifies `PRAGMA integrity_check == 'ok'` on the live DB.
#
# Configurable threshold:
#   - Default logrotate trigger: `size 100M` (100 MB)
#   - Runtime override: export `HYPERSTITION_SQLITE_MAX_MB` (default `100`) or `HYPERSTITION_SQLITE_MAX_BYTES`.

/tmp/hyperstition-api-telemetry.db /var/lib/hyperstitionstud.io/api-telemetry.db {
    size 100M
    rotate 12
    compress
    delaycompress
    missingok
    notifempty
    nocreate
    sharedscripts
    prerotate
        TARGET_DB="${1:-${HYPERSTITION_TELEMETRY_DB_PATH:-/tmp/hyperstition-api-telemetry.db}}"
        MAX_MB="${HYPERSTITION_SQLITE_MAX_MB:-100}"
        MAX_BYTES="${HYPERSTITION_SQLITE_MAX_BYTES:-$((MAX_MB * 1024 * 1024))}"
        ROTATE_KEEP="${HYPERSTITION_SQLITE_ROTATE_KEEP:-12}"
        PYTHON_BIN="${HYPERSTITION_PYTHON_BIN:-python3}"
        PYTHONPATH="${PYTHONPATH:-/srv/hyperstitionstud.io/repos/hyperstitionstudio-core/src:/workspace/hyperstitionstudio-core/src}" \
            "${PYTHON_BIN}" -m hyperstitionstud_io.db.sqlite_meta \
            --truncate-quiescent \
            --compress-archive \
            --rotate-keep "${ROTATE_KEEP}" \
            --db "${TARGET_DB}" \
            --max-bytes "${MAX_BYTES}"
    endscript
}
