"""Retention: remove backups older than a repository's policy, reclaim space.
Point-in-time retention. With "keep restore points for N days", every
backup taken in the last N days can still be restored exactly. A version
is removed only when no restore point in that window needs it:
* it was replaced or deleted before the window started (``valid_to`` is
before the cutoff), or
* it is a deletion marker older than the window (the item was deleted from
Microsoft 365 more than N days ago).
So anything still in Microsoft 365 is always kept, however old, and items
deleted from Microsoft 365 stay restorable for N days after deletion.
Objects on hold are never touched.
After the catalog is pruned, blobs nothing refers to any more are deleted
from the repository (:meth:`Repository.compact`). That step holds the
repository's lock exclusively, so it never overlaps a backup.
"""
from __future__ import annotations
from dataclasses import asdict, dataclass
from datetime import UTC, datetime, timedelta
from typing import Any
from pydantic import Field
from sqlalchemy import and_, delete, exists, func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from s365b.core import runlog, settings_store
from s365b.core.audit import audit
from s365b.core.events import emit
from s365b.core.generation import catalog_behind
from s365b.core.logging import get_logger
from s365b.core.services import Services
from s365b.core.settings_store import SettingsGroup
from s365b.db.models import (
AuditLog,
Event,
Item,
ItemVersionRow,
JobRun,
JobRunLog,
ProtectedObjectRow,
RepositoryConfig,
RunKind,
RunStatus,
)
from s365b.jobs.liveness import heartbeat
from s365b.jobs.locks import RepositoryBusyError, repository_lock
from s365b.modules.sdk import Severity
from s365b.storage.repository import content_blobs
[docs]
log = get_logger(__name__)
[docs]
RETENTION_FAILED = "retention_failed"
[docs]
class HousekeepingSettings(SettingsGroup):
"""How long the app keeps its own records, and when retention runs.
Attributes:
audit_log_days: Audit log entries older than this are deleted.
Six years by default, a common choice for compliance programs.
alert_days: Alerts (events) older than this are deleted.
run_log_days: Job runs' own logs older than this are deleted (the
runs themselves are kept).
run_hour: Hour of the day (server time) when retention runs.
"""
[docs]
audit_log_days: int = Field(2192, ge=30, le=36500)
[docs]
alert_days: int = Field(365, ge=7, le=36500)
[docs]
run_log_days: int = Field(90, ge=7, le=36500)
[docs]
run_hour: int = Field(3, ge=0, le=23)
[docs]
def keep_days(repo: RepositoryConfig) -> int | None:
"""A repository's retention period in days; ``None`` means forever."""
days = (repo.retention or {}).get("keep_days")
return int(days) if days else None
def _expired(repository_fk: int, cutoff: datetime) -> Any:
"""SQL condition for versions retention may remove."""
held = exists().where(
ProtectedObjectRow.id == Item.protected_object_fk, ProtectedObjectRow.hold.is_(True)
)
return and_(
ItemVersionRow.repository_fk == repository_fk,
Item.id == ItemVersionRow.item_fk,
~held,
or_(
and_(ItemVersionRow.valid_to.is_not(None), ItemVersionRow.valid_to <= cutoff),
and_(ItemVersionRow.deleted.is_(True), ItemVersionRow.valid_from <= cutoff),
),
)
@dataclass(slots=True)
[docs]
class Preview:
"""What a retention policy would remove now.
Attributes:
versions: Item versions removed.
items: Items removed entirely (no version left).
size: Logical size of the removed versions. Space actually freed
is usually less: content shared with kept versions stays.
held_objects: Objects on hold, whose backups are kept regardless.
cutoff: Start of the kept window; ``None`` for "keep forever".
"""
[docs]
cutoff: datetime | None = None
[docs]
async def preview(
s: AsyncSession, repository_fk: int, days: int | None, now: datetime | None = None
) -> Preview:
"""Count what a policy of ``days`` would remove from a repository now.
Args:
s: Database session.
repository_fk: Repository.
days: Retention period; ``None`` for forever.
now: Current time.
Returns:
The counts.
"""
held = (
await s.execute(
select(func.count()).select_from(ProtectedObjectRow).where(ProtectedObjectRow.hold)
)
).scalar_one()
if not days:
return Preview(held_objects=held)
cutoff = (now or datetime.now(UTC)) - timedelta(days=days)
cond = _expired(repository_fk, cutoff)
versions, size = (
await s.execute(
select(func.count(), func.coalesce(func.sum(ItemVersionRow.size), 0))
.select_from(ItemVersionRow)
.join(Item, Item.id == ItemVersionRow.item_fk)
.where(cond)
)
).one()
# Items all of whose versions in this repository expire.
per_item = (
select(ItemVersionRow.item_fk)
.join(Item, Item.id == ItemVersionRow.item_fk)
.where(ItemVersionRow.repository_fk == repository_fk)
.group_by(ItemVersionRow.item_fk)
.having(
func.bool_and(
or_(
and_(ItemVersionRow.valid_to.is_not(None), ItemVersionRow.valid_to <= cutoff),
and_(ItemVersionRow.deleted.is_(True), ItemVersionRow.valid_from <= cutoff),
)
)
)
.where(
~exists().where(
ProtectedObjectRow.id == Item.protected_object_fk, ProtectedObjectRow.hold
)
)
)
items = (await s.execute(select(func.count()).select_from(per_item.subquery()))).scalar_one()
return Preview(int(versions), int(items), int(size), held, cutoff)
async def _prune(services: Services, repository_fk: int, cutoff: datetime) -> tuple[int, int]:
"""Delete expired versions in batches, then items left without versions."""
versions = 0
while True:
async with services.db.session() as s:
ids = (
(
await s.execute(
select(ItemVersionRow.id)
.join(Item, Item.id == ItemVersionRow.item_fk)
.where(_expired(repository_fk, cutoff))
.limit(DELETE_BATCH)
)
)
.scalars()
.all()
)
if not ids:
break
await s.execute(delete(ItemVersionRow).where(ItemVersionRow.id.in_(ids)))
versions += len(ids)
async with services.db.session() as s:
orphans = await s.execute(
delete(Item).where(~exists().where(ItemVersionRow.item_fk == Item.id))
)
items = int(getattr(orphans, "rowcount", 0) or 0)
return versions, items
[docs]
CATALOG_BEHIND = (
"No space was reclaimed: this repository holds backups this server's database does "
"not know about (the repository was connected to a new database, or an older "
"database backup was restored). Retention keeps them all. Restore the newest "
"database backup to reclaim space again."
)
async def _live_blobs(services: Services, repository_fk: int) -> set[str]:
"""Every blob the catalog still refers to in a repository."""
live: set[str] = set()
async with services.db.session() as s:
result = await s.stream_scalars(
select(ItemVersionRow.content)
.where(
ItemVersionRow.repository_fk == repository_fk,
ItemVersionRow.content.is_not(None),
)
.execution_options(yield_per=5000)
)
async for content in result:
live.update(content_blobs(content))
return live
[docs]
async def run_retention(
services: Services, repository_fk: int, *, requested_by: str = "scheduler"
) -> tuple[int, bool]:
"""Apply a repository's retention policy and reclaim space.
Args:
services: Process services.
repository_fk: Repository.
requested_by: Who started it.
Returns:
The job run ID, and whether it was skipped because a backup was
writing to the repository (the caller retries later).
"""
db = services.db
now = datetime.now(UTC)
async with db.session() as s:
repo = await s.get(RepositoryConfig, repository_fk)
if repo is None:
raise ValueError(f"repository {repository_fk} does not exist")
days = keep_days(repo)
run = JobRun(
kind=RunKind.RETENTION,
status=RunStatus.RUNNING,
requested_by=requested_by,
started_at=now,
stats={"repository": repo.name, "keep_days": days},
progress={"phase": "retention", "updated_at": now.isoformat()},
)
s.add(run)
await s.flush()
run_id, repo_name = run.id, repo.name
runlog.for_run(run_id)
bound = log.bind(run_id=run_id, repository=repo_name)
stats: dict[str, Any] = {"repository": repo_name, "keep_days": days}
status, error, skipped = RunStatus.SUCCESS, None, False
try:
async with (
repository_lock(db, repository_fk, exclusive=True, wait=False),
# Pruning and compaction report no progress: without this, a long
# run would be marked interrupted while it is still working.
heartbeat(db, run_id),
):
if days:
cutoff = now - timedelta(days=days)
stats["cutoff"] = cutoff.isoformat()
stats["versions_removed"], stats["items_removed"] = await _prune(
services, repository_fk, cutoff
)
async with db.session() as s:
repo = await s.get(RepositoryConfig, repository_fk)
assert repo is not None # noqa: S101 - checked above
opened = await services.open_repository(repo)
ahead = await catalog_behind(db, repository_fk, opened)
if ahead is not None:
# The database is older than the repository: data it does not
# know about would look unreferenced. Keep everything.
status, error = RunStatus.WARNING, CATALOG_BEHIND
stats["space_reclaimed"] = False
else:
live = await _live_blobs(services, repository_fk)
stats |= asdict(await opened.compact(live))
except RepositoryBusyError:
status, skipped = RunStatus.CANCELLED, True
error = "Skipped: a backup was writing to this repository. Retention tries again later."
except Exception as exc:
bound.exception("retention.failed")
status, error = RunStatus.FAILED, f"{type(exc).__name__}: {exc}"
async with db.session() as s:
row = await s.get(JobRun, run_id)
assert row is not None # noqa: S101 - created above
row.status, row.error, row.stats = status, error, stats
row.finished_at = datetime.now(UTC)
row.progress = {"phase": "done"}
if not skipped:
await audit(s, requested_by, "retention.run", target=repo_name, details=stats)
if status is RunStatus.FAILED or error == CATALOG_BEHIND:
await emit(
s,
RETENTION_FAILED,
Severity.ERROR if status is RunStatus.FAILED else Severity.WARNING,
f"Retention failed: {repo_name}"
if status is RunStatus.FAILED
else f"Retention reclaimed no space: {repo_name}",
body={"error": error, "repository": repo_name},
dedup_key=f"retention_failed:{repository_fk}",
run_fk=run_id,
)
bound.info(
"retention.finished",
status=status.value,
**{k: v for k, v in stats.items() if isinstance(v, int)},
)
return run_id, skipped
[docs]
async def purge_records(services: Services, now: datetime | None = None) -> dict[str, int]:
"""Delete audit log entries, alerts and run logs older than the housekeeping settings.
Args:
services: Process services.
now: Current time.
Returns:
Rows deleted per table.
"""
now = now or datetime.now(UTC)
async with services.db.session() as s:
cfg = await settings_store.load(s, HousekeepingSettings)
audit_rows = await s.execute(
delete(AuditLog).where(AuditLog.at < now - timedelta(days=cfg.audit_log_days))
)
event_rows = await s.execute(
delete(Event).where(Event.created_at < now - timedelta(days=cfg.alert_days))
)
log_rows = await s.execute(
delete(JobRunLog).where(JobRunLog.at < now - timedelta(days=cfg.run_log_days))
)
return {
"audit_log": int(getattr(audit_rows, "rowcount", 0) or 0),
"events": int(getattr(event_rows, "rowcount", 0) or 0),
"run_log": int(getattr(log_rows, "rowcount", 0) or 0),
}