Watch, Lease and history
Watch, Lease and history share pgetcd’s transaction and revision model. The event log in etcd.events is durable. Watch cursors and Lease deadlines are runtime state derived from committed PostgreSQL facts.
Complete revisions
Each tenant gateway runs one Watch service with one concurrent tail operation. Tail v2 (etcd._tail_v2), the internal event-reading interface, reads metadata, events and the revision manifest from a single snapshot. It checks the event count and encoded-size budgets, then certifies the scanned high-watermark before delivering events.
The internal cursor is (revision, sub), where sub is the zero-based event sequence number within a revision. Delivery advances only across complete revisions. Client revisions can have gaps because a Watch can select a key range or filter event types.
In the rules below, R is the current revision and C is the logical compact revision:
| Request | Result |
|---|---|
start_revision = 0 | Start at R + 1, using the certified creation snapshot |
Explicit start_revision > C | Include matching events at that revision and later revisions |
0 < start_revision <= C | Create the watch, then immediately emit a canceled WatchResponse with compact_revision = C |
start_revision > R | Wait for future commits; do not claim catch-up until R reaches that revision |
A Created response confirms registration; it does not confirm that historical events have already been delivered. If a large revision is split across multiple WatchResponse fragments, only the final fragment completes that revision.
Progress and backpressure
WatchProgressRequest obtains a new certified revision R. The stream first delivers all matching events through R. It broadcasts a progress response with watch_id = -1 only when all active watches on the stream are caught up and their start_revision values permit that watermark. A future or lagging Watch on the same stream blocks the broadcast.
Automatic per-Watch progress (progress_notify = true) uses its configured interval (watch.progress_interval_ms). Progress always reflects a certified scan, even when filtering produces no events.
PostgreSQL LISTEN / NOTIFY messages are wake hints only; they carry no authority to advance a cursor. Periodic polling (watch.poll_interval_ms) recovers missed notifications. The implementation never substitutes a notification counter for the durable event log.
Per-watcher queues enforce message, byte and lag limits (watch.queue_capacity). A slow consumer receives an explicit ResourceExhausted termination; the service never silently drops events or mislabels queue pressure as compaction.
To reconnect after a stream break, resume from last_complete_revision + 1 or from a valid progress watermark header.revision + 1. Do not use a Created header or an unrelated Range header as evidence that earlier Watch events were delivered. Performing a full Range relist followed by Watch(start_revision = range_header.revision + 1) is also a valid recovery procedure.
Lease facts and deadlines
The logged etcd.leases row stores the Lease ID, a fresh 128-bit grant generation (grant_hi, grant_lo), the granted TTL, and the committed renewal sequence (renew_seq). Shared-memory runtime state stores the background worker generation, the last observed committed renew_seq, and a monotonic clock deadline. The 128-bit grant generation prevents a stale expiry task from revoking a newly granted Lease that reuses the same 64-bit Lease ID.
Any call that references a Lease locks etcd.meta and then locks the etcd.leases row. Before deciding whether the Lease has expired, it refreshes shared-memory runtime state from any newer committed renew_seq. The extension never holds a shared-memory spinlock or LWLock while waiting for a PostgreSQL row lock.
A successful LeaseKeepAlive renewal requires its own synchronous COMMIT. A rolled-back transaction never extends the runtime deadline. When a background worker observes a new committed renew_seq, it conservatively grants a full TTL starting from that observation timestamp.
Expiry re-verifies the Lease ID, grant generation, renew_seq and worker generation inside a transaction. It then revokes the Lease and deletes all attached keys atomically. If one or more attached keys are deleted, they share a single new revision R + 1; if no keys were attached, R does not advance.
The attachment ledger on etcd.leases bounds the eventual revoke cost before keys are attached (max_keys_per_lease = 4096, max_lease_revoke_bytes = 8388608). See Compatibility.
Worker recovery
When pg_etcd is loaded via shared_preload_libraries, its launcher supervises one connected background worker per database listed in pg_etcd.lease_databases (up to eight databases). A connected worker is bound to its target database and cannot switch databases at runtime.
On PostgreSQL restart or worker restart, tenant readiness closes while a new worker generation reconstructs runtime Lease state from etcd.leases and grants each surviving Lease a full granted_ttl_sec from the reconstruction timestamp. Tenant readiness reopens only after reconstruction succeeds. Missing worker slots, a missing extension, or an ABI mismatch keeps /readyz unready (503).
This conservative policy prevents premature Lease deletion across restarts at the cost of delayed expiry. A single restart can add up to one full granted_ttl_sec plus recovery time; repeated faults have no fixed upper bound on latest expiry. This differs from upstream etcd’s remaining-TTL checkpoint behavior.
Compaction and history
In etcd.meta, C is the logical compact revision and F is the physical history floor. Fresh state uses R = 1, C = -1, F = 0. After the first compaction, 0 <= F <= C <= R.
Compact advances C without consuming a KV revision. The synchronous implementation constructs a complete new anchor generation in etcd.history_anchor, publishes that generation, and sets F = C in the same transaction. It then deletes rows in etcd.events and etcd.revision_manifest strictly below F, along with older anchor generations.
The anchor stores a complete baseline of live keys at revision F. Historical Range at revision rev (C <= rev <= R) combines the baseline at F with events in (F, rev]. Events at revision F itself remain in etcd.events for Watch delivery, including deletion tombstones, so a tombstone at the boundary still hides an older value.
If anchor construction fails or rolls back, F and C remain unchanged. While Compact accepts the physical boolean field in protobuf requests, Compact(physical = true) is not claimed as a physical OS disk-space reclamation API; internal table cleanup runs transactionally inside PostgreSQL. See Schema and Compatibility.
Source: internal/watch/, extension/pg_etcd.c, extension/pg_kvcore/lease_worker.c, and extension/pg_kvcore/lease_runtime.c.
