# Lifecycle and Object Lock

> How lifecycle rules and retention work under leases.

---

LLMS index: [llms.txt](/llms.txt)

---

> [!NOTE]
> Object Lock (`GOVERNANCE` / `COMPLIANCE` retention and legal hold) and bucket lifecycle rules (version expiration, expired delete-marker cleanup, and incomplete multipart upload abort) are **Preview** features in the MVP release.

In Silo's erasure-coded backend, lifecycle expiration and Object Lock checks rely on the distributed disk scanner (`NSScanner`), in-memory expiry queues, and handler-level pre-checks. Directly enabling those paths on a shared PostgreSQL backend would fail in four ways:

1. **MultiDelete TOCTOU window**: Silo's `DeleteObjects` handler pre-checked Object Lock retention before calling the backend delete loop, leaving a race window where a concurrent request could enable a legal hold or extend retention before the row was deleted.
2. **Unbounded version slices in `Evaluator.Eval`**: the upstream lifecycle evaluator expects all versions of a key in a single in-memory slice, which would allocate unbounded gateway memory on keys with deep version histories.
3. **Subtree vs. exact-key delete mismatch**: erasure-coded lifecycle `DeleteAll` passes `DeletePrefix=true, DeletePrefixObject=true` to delete all versions of an exact key, which a naive prefix delete would misinterpret as deleting an entire `/` key subtree.
4. **Missing `AbortIncompleteMultipartUpload` rule wiring**: upstream rule structs lacked complete `AbortIncompleteMultipartUpload` evaluation fields and relied on a global stale-upload timer rather than per-bucket prefix and initiation-age rules.

This page describes how `pgsilo` implements authoritative Object Lock enforcement and fenced lifecycle execution directly in PostgreSQL.

## 1. Authoritative Object Lock in the database state machine {#object-lock-state-machine}

Rather than trusting unvalidated JSON headers in `user_defined`, `pgsilo` stores normalized lock columns on `silo.objects` (`retention_mode`, `retain_until`, `legal_hold`) and default retention settings on `silo.buckets` (synchronized transactionally whenever `.metadata.bin` is saved under the bucket `FOR UPDATE` lock):

- **Database UTC clock**: all retention expiration checks compare `retain_until` against PostgreSQL's `clock_timestamp()` inside the key lock, ensuring S3 requests, `silo_api` SQL calls, and background lifecycle workers agree on a single clock.
- **Every mutation path shares one check**:
  - **Single `DeleteObject` and batch `DeleteObjects`**: each key deletion runs inside the per-key advisory lock (`silo.lock_key`), re-reading the target version's `retention_mode`, `retain_until`, and `legal_hold` atomically so no TOCTOU window exists between pre-check and deletion.
  - **`PutObjectMetadata` (`?retention` / `?legal-hold`)**: modifies retention and legal hold in place on the target version without creating a new version or altering the object ETag. Shortening `COMPLIANCE` retention or switching `COMPLIANCE` to `GOVERNANCE` before expiration is rejected even for the S3 root user.
  - **Governance bypass**: requires both an explicit `x-amz-bypass-governance-retention: true` header and `s3:BypassGovernanceRetention` authorization evaluated per target version (plus `UPDATE` on the bucket ACL relation under `iam_and_pg`). Governance bypass never overrides `COMPLIANCE` retention or an active `legal_hold`.
  - **SQL `silo_api` integration**: `silo_api.put_object` and `copy_object` automatically apply default bucket retention on object-lock buckets, while `silo_api.delete_object` enforces retention and legal hold with no governance bypass parameter.
  - **Force bucket deletion blocked**: `DELETE /{bucket}` with `x-minio-force-delete` is rejected with HTTP `405` on any object-lock-enabled bucket, even when the bucket is empty.

## 2. Streaming keyset lifecycle scanner and executor {#lifecycle-scanner}

Instead of running the erasure-coded `NSScanner`, writable `pgsilo` gateways run a PostgreSQL-native lifecycle worker covering four rule actions (remote storage tiering `Transition` and `RestoreObject` are rejected at configuration time):

1. **Current version expiration (`Expiration` by `Days` or `Date`)**: deletes the current object in an unversioned bucket, inserts a delete marker in a versioned bucket (without duplicating an existing latest delete marker), or applies null-version expiration in a suspended bucket.
2. **Noncurrent version expiration (`NoncurrentVersionExpiration`)**: computes noncurrent age from the creation timestamp of the version's **successor** (`noncurrent_since`), not the old version's own `mod_time`, and preserves at least `NewerNoncurrentVersions` newer historical versions before deleting eligible versions.
3. **Expired object delete marker cleanup (`ExpiredObjectDeleteMarker`)**: removes a current delete marker when it is the only remaining version row for that key.
4. **Incomplete multipart upload cleanup (`AbortIncompleteMultipartUpload`)**: matches active uploads in `silo.uploads` by rule prefix and `initiated` age and aborts them atomically, cascading deletion of uploaded parts and segments.

To keep memory bounded, the scanner iterates over buckets and keys using **keyset pagination** (`(key COLLATE "C", commit_seq)` for objects and `(key, initiated, upload_id)` for multipart uploads) reading only metadata columns—never decrypting or loading SSE-C / SSE-S3 object bodies.

Before executing any deletion or marker insertion, the worker locks the target key (`silo.lock_key`), re-reads the current version chain and bucket lifecycle configuration revision, and re-verifies Object Lock protections. If a concurrent `PUT`, tag change, legal hold, or rule update occurred after the scan pass, the stale candidate becomes a safe no-op.

## 3. Multi-gateway maintenance leases and epoch fencing {#lease-fencing}

When multiple writable gateways share a PostgreSQL primary, only one gateway should execute background lifecycle and annotation cleanup at a time, and a partitioned or paused leader must never commit stale deletions after another gateway takes over.

`pgsilo` coordinates background workers through a database lease table (`silo.TryLifecycleLock`) rather than a long-lived session advisory lock on the coordination pool:

- **Short-transaction lease claims and renewals**: a writable primary gateway claims or renews the maintenance lease in a short transaction using PostgreSQL's clock. Whenever a different gateway takes over an expired lease, the database increments a monotonic **`epoch`** counter.
- **Transactional epoch fencing**: every destructive lifecycle or annotation-cleanup batch locks the lease row (`FOR SHARE`) inside the same transaction as the object/annotation deletion and verifies that `(owner_id, epoch)` still matches the worker's lease and has not expired. If a new leader has incremented `epoch`, the old worker's transaction aborts before committing.
- **Standby and read-only safety**: gateways with `SILO_PG_READ_ONLY=on` or connected to a database where `pg_is_in_recovery() = true` never claim the maintenance lease. Lease ownership and errors are exported at `/minio/metrics/v3/pg` via `minio_pg_lifecycle_leader` and `minio_pg_lifecycle_errors_total`.

---

Backlinks:

- [Design](/docs/s3/design/)
