# Architecture, Safety & Verification ## Design Philosophy `pgbreaker` puts only the minimal fast-fail primitives inside PostgreSQL that cannot be replicated cleanly outside the kernel: integer-key concurrency control/tripping and lock-free GCRA QPS limiting for PostgreSQL **14–18**. Policy orchestration, SQL auditing, queueing, and cluster-wide rule distribution stay external. --- ## Two-Layer Module Seam ```text +-----------------------------------------------------------------------+ | PostgreSQL Backend Warm Hot Path (zero LWLock, zero palloc, no strings)| | src/pg/pgb_hooks.c --> PgbLocalSnapshot (epoch-synced) | | | | | | v v | | src/core/ (ZERO postgres.h dependency) | | - pgb_matcher.c : present_mask + expected O(1) hash lookup | | - pgb_limiter.c : eval_state pin + packed CAS & 64-bit GCRA CAS | | - pgb_ledger.c : fixed 32-level per-backend slot stack | +-----------------------------------------------------------------------+ | ^ single-word atomic CAS epoch refresh / startup v | +-----------------------------------------------------------------------+ | Fixed Preallocated Shared Memory (< 256 KB @ max_rules = 1024, 64B CL)| | src/pg/pgb_shmem.c : PgbShmemHeader + PgbRuleSlot[max_rules] | | src/pg/pgb_api.c : 5 SQL functions + 2 SRFs (decoupled I/O locks) | | Disk persistence : $PGDATA/pg_stat/pgbreaker.rules (v1, CRC32C) | +-----------------------------------------------------------------------+ ``` | Layer | Files | Responsibilities | | :--- | :--- | :--- | | **Core engine (`src/core/`)** | `pgb_atomic.h`, `pgb_core.h`, `pgb_matcher.c`, `pgb_limiter.c`, `pgb_ledger.c` | Pure C99/C11 with zero `postgres.h` dependency. Compiles standalone under ASan, UBSan, and TSan (`-DPGB_USE_PG_ATOMICS` switches atomics to PG `port/atomics.h` with `pg_memory_barrier()` acquire/release semantics for weakly-ordered CPUs such as ARM64). Enforces GCC/Clang alignment (`PGB_ALIGNAS`) and native 64-bit atomics at compile time (`PGB_CACHELINE_SIZE` defaults to 64 B, overrideable for 128 B architectures). | | **PG adapter (`src/pg/`)** | `pgb_pg.h`, `pgb_shmem.c`, `pgb_hooks.c`, `pgb_api.c` | PG 14–18 compatibility macros, fixed shared memory, backend-local snapshot refresh, executor/xact/subxact/log/exit hooks, atomic file persistence, and SQL API. | --- ## Lock-Free Hot Path Internals 1. **Empty / Disabled Fast-Path**: `ExecutorStart` maintains balanced `pgb_nesting_level` unconditionally across all four executor hooks (`ExecutorStart`/`ExecutorRun`/`ExecutorFinish`/`ExecutorEnd`), then checks `pgb_enabled` and performs a single relaxed atomic load of `rule_count`. When disabled or zero rules are configured, enforcement is skipped immediately. 2. **Epoch-Driven Local Snapshot**: each backend keeps a read-only `PgbLocalSnapshot` allocated once in `TopMemoryContext`. In steady state (`cached_epoch == rule_epoch`), zero `LWLock`s are acquired and lookups take expected O(1) time in the local open-addressing hash table filtered by `present_mask`. A snapshot rebuild acquires `pgb_shmem->lock` (`LW_SHARED`) briefly once after a control-plane mutation bumps `rule_epoch`, skips any retired slot (`!in_use` or `PGB_EVAL_RETIRED_BIT`), and returns `false` (clearing `cached_epoch`) rather than marking a truncated snapshot current; disk `fsync` runs under a separate `persist_lock` so I/O never blocks hot-path refreshes or emergency trips. 3. **Cacheline Isolation, Quiescent Slot Pinning & ABA-Free Concurrency CAS**: each `PgbRuleSlot` is compile-time verified at `2 * PGB_CACHELINE_SIZE` (128 bytes on 64B cachelines), separating read-mostly metadata on cacheline 0 from hot atomics on cacheline 1: - `eval_state` packs `(gen_tag << 32) | retired_bit | eval_pins` into one 64-bit atomic word. Both `pgb_try_acquire()` and `pgb_release()` pin `eval_state` across 64-bit `rule_gen` validation, `active_state` CAS, GCRA, and telemetry updates, and unpin before returning. Retired slots (`pgb_slot_retire` clears `in_use = false` and sets `retired_bit`) are only reactivated once quiescent (`retired && eval_pins == 0`), preventing stale evaluators or delayed releases from touching a replacement rule's counters, `active_state`, or GCRA state (unconditionally ABA-free). - `active_state` packs `((uint32_t)rule_gen << 32) | active_count` into one 64-bit atomic word for single-word atomic CAS validation and saturating decrement. - **Single-RMW decision telemetry**: each decision increments exactly one mutually exclusive counter (`allows_total`, `rejects_total`, or `shadows_total`), avoiding double atomic writes on reject/shadow paths; `pgb_slot_read_stats()` computes `hits_total = allows + rejects + shadows` from one load per counter so `rules_view` always reports `hits_total >= rejects_total + shadows_total` even across `reset_stats()`. 4. **Single-Word CAS GCRA QPS Limiter**: `CLOCK_MONOTONIC` is read only when the matched rule sets `max_qps > 0` (or on rejection when `pgbreaker.log_rejects = on`). Pure concurrency/trip rules issue **zero clock syscalls** on normal execution. GCRA uses conservative ceiling intervals (`ceil(1e9 / max_qps)` ns), never rewinds `gcra_tat_ns` on stale/delayed samples, fails closed if timestamp arithmetic would overflow `UINT64_MAX`, fails open if `clock_gettime` itself fails, and immediately rolls back any acquired concurrency slot (via internal `pgb_release_pinned`) on GCRA reject. 5. **Fixed 32-Level Slot Ledger**: every acquired concurrency lease is recorded in the backend's `PgbSlotLedger` with `(slot_idx, rule_gen, subxid, cookie)` where `cookie = (uintptr_t)queryDesc`. If the 32-entry ledger is full, enforced concurrency rules fail closed with `53P01` (`reason=concurrency_limit`) while shadow mode skips slot acquisition cleanly. Leases unwind deterministically across: - Normal completion: `ExecutorEnd_hook` (cookie-matched pop, cursor-safe). - Startup / execution / finish error: `PG_CATCH` in `ExecutorStart_hook`, `ExecutorRun_hook`, and `ExecutorFinish_hook` (releases failed parent cursors inside child savepoints immediately). - Query error / `statement_timeout` / `pg_cancel_backend`: `RegisterXactCallback` (`XACT_EVENT_ABORT`, `COMMIT`, `PREPARE`). - `SAVEPOINT` rollback / commit: `RegisterSubXactCallback` (`SUBXACT_EVENT_ABORT_SUB` drains aborted subxact entries; `SUBXACT_EVENT_COMMIT_SUB` reparents entries to parent subxid). - `pg_terminate_backend` / backend exit: lazily registered `before_shmem_exit` drains all remaining slots. --- ## Node-Local Atomic Persistence `pgbreaker` requires no Background Worker, no SPI, and no catalog tables: - Control-plane rule mutators (`trip`, `set_rule`, `remove_rule`, `clear_rules`) publish changes into shared memory immediately under `lock` (`LW_EXCLUSIVE`), then flush under `persist_lock` via interruptible `LWLockConditionalAcquire` polling so slow disk I/O never stalls emergency rule publication. - Persistence writes a host-endian v1 file: a 20-byte `PgbPersistHeader` (magic `0x50474252`, format version `1`, `rule_count`, `next_rule_id`, `pg_crc32c`) plus 40-byte `PgbPersistRule` records to a unique temp file (`$PGDATA/pg_stat/pgbreaker.rules.tmp..`, opened `O_CREAT | O_EXCL | O_NOFOLLOW`), flushed with `pg_fsync`, swapped via direct atomic `rename()` + parent directory `fsync` (honoring PostgreSQL's `fsync` GUC). - `shmem_startup_hook` cleans up stale `pgbreaker.rules.tmp.*` temp files, opens the state file with `O_RDONLY | O_NONBLOCK | O_NOFOLLOW` and checks `S_ISREG` before reading, validating CRC32C and checking duplicate `rule_id`/key entries in $O(N \log N)$ time. - Missing files (`ENOENT`) boot silently with `0` rules; non-regular, unreadable, truncated, corrupt, or incompatible files emit a `WARNING` and boot with `0` rules (**Fail-Open**). Lowered `max_rules` loads the first `max_rules` entries, sets `status.persisted = false`, and preserves the oversized file on disk until `clear_rules()`. --- ## Safety Invariants 1. **No self-lock**: exempts effective `superuser()`, roles inheriting `pg_use_reserved_connections` (PG 16+, cached with `AUTHOID`/`AUTHMEMMEMROLE`/`AUTHMEMROLEMEM` syscache invalidation), `IsParallelWorker()`, `EXEC_FLAG_EXPLAIN_ONLY`, bootstrap mode, nested executor statements (`nesting_level > 0`), and `ProcessUtility` work that does not invoke the executor (`VACUUM`, `ANALYZE`, DDL). `pgbreaker.enabled = off` (`SIGHUP`) provides hot bypass. 2. **Zero slot leaks**: multi-exit unwinding (`ExecutorStart`/`Run`/`Finish` `PG_CATCH`, `ExecutorEnd`, xact/subxact callbacks, `before_shmem_exit`) with `eval_state` pinning, `rule_gen` validation, and saturating decrement. 3. **Fail-Open startup & bounded server logs**: corrupt/missing state files never block PostgreSQL startup; `emit_log_hook` suppresses raw `53P01` server error spam (`0` extension lines when `log_rejects = off`, atomically capped at `10` `LOG` lines/sec via single 64-bit monotonic CAS when `on`). 4. **Standby-safe control plane**: node-local shmem + file persistence lets read-only standbys run `trip()` / `set_rule()` locally without touching the primary (`pg_basebackup` copies the persisted file in `$PGDATA/pg_stat/` as the standby's initial seed, after which nodes diverge independently). 5. **Control-plane discipline**: schema-hijack install guard, least-privilege SQL grants (`REVOKE ALL FROM PUBLIC`, `pg_read_all_stats` for views), C-level `superuser()` enforcement on all mutators, and `reset_stats()` preserving `active_count`. --- ## Explicit Non-Goals | Out of Scope | Recommended Layer / Alternative | | :--- | :--- | | SQL auditing, injection firewall, DDL guards | `pg-safeupdate`, `pg_savior`, SQL gateway | | Regex, SQL text, table-name, or `application_name` matching | ProxySQL, PgDog, application middleware | | In-backend wait queues | PgBouncer, Odyssey (queuing in PG holds `max_connections` & `xmin`) | | Cross-node rule replication | Patroni, Ansible, external control plane | | Adaptive heuristics, business priority scoring & TTL scheduling | External orchestrator / `pg_cron` | | Connection storm protection | PgBouncer, Odyssey | | Static planner cost filtering (`max_cost`) | `pg_plan_filter` | --- ## Testing & Verification ### Running the Suites ```bash # Standalone core suite (no PostgreSQL required): # C99 & C11 Clang ASan+UBSan, C99 & C11 Clang TSan (64-thread stress), and GCC -O2 Release make test-core # End-to-end PostgreSQL integration, chaos, hot standby & pgbench suite make && sudo make install make test-pg # full suite including pgbench (12 suites) SKIP_BENCH=1 make test-pg # fast CI mode (11 suites, ~16s) ``` Override compilers or `pg_config` as needed: ```bash make SAN_CC=clang CORE_CC=gcc test-core make PG_CONFIG=/usr/pgsql-16/bin/pg_config && sudo make PG_CONFIG=/usr/pgsql-16/bin/pg_config install ``` ### Verified Test Matrix (v0.1.0) - **Core engine (`tests/core/test_pgb_core.c`)**: **17/17 suites** across 5 standalone builds (C99 & C11 Clang ASan+UBSan, C99 & C11 Clang TSan with 64-worker + control-plane churner stress, live `pgb_try_acquire` + deterministic `eval_state` pin rendezvous, per-window `pgb_log_rate_allow` oracle, GCRA stale-timestamp / `!clock_ok` preservation / overflow checks, subxact & full drains, duplicate-release probes, and GCC `-O2` Release) — `0` warnings, `0` leaks, `0` data races. - **PostgreSQL 14–18 CI & Integration Suite (`tests/pg/run_pg_tests.sh`)**: Unix-socket-only isolated primary + hot-standby clusters running with default `compute_query_id = 'auto'` (verifying `EnableQueryId()`): 1. Control API (`CREATE EXTENSION pgbreaker` under restrictive default privileges, schema-hijack rejection including `CREATE DOMAIN`, `trip`, `trip(0)` `22023`, `set_rule` live upsert & explicit-`NULL` `22023`, non-transactional `ROLLBACK`, `remove_rule`, `clear_rules`, `reset_stats` preserving live `active_count`, `rules` & `status` views including `persisted`, dropped-role `NULL`, and un-preloaded `55000` errors) 2. Enforcement (`SQLSTATE 53P01` + `DETAIL`) vs per-rule & `SIGHUP` global `shadow`, and `emit_log_hook` server-log suppression (`0` lines when `off`, `<= 10` `LOG` lines/window when `on`, without suppressing unrelated user `53P01` errors) 3. `SIGHUP` emergency bypass (`pgbreaker.enabled = off / on`) 4. Effective-role enforcement (`SET ROLE`, PG 16+ `pg_use_reserved_connections` including `WITH INHERIT FALSE` and live `GRANT`/`REVOKE`), `EXPLAIN`-only, real parallel workers (`Workers Launched >= 1`, leader `hits_total = 1`), direct ACL & `pg_read_all_stats` vs `pg_monitor` `persist_path` isolation, C-level `superuser()` auth, and `(q,d,r) > (q,0,0)` precedence 5. Concurrency enforcement (`max_concurrency = 2` with deterministic advisory-lock barriers and bounded `lock_timeout` probes, `active_count = 0`) 6. Zero-leak chaos: pooled-connection checks after `ERROR`/`statement_timeout`/`pg_cancel_backend`, `pg_terminate_backend` (`57P01`), `SAVEPOINT`/`ROLLBACK TO SAVEPOINT`/`RELEASE SAVEPOINT`, `WITH HOLD` cursors, `NO SCROLL` backward-fetch portal cleanup, returned `refcursor` deferred admission, `SCROLL` + `MOVE ABSOLUTE 0` rewind safety, out-of-order multi-cursor close, failing parent cursor inside child savepoint with sibling cursor live, 32-cursor ledger-full `53P01` rejection, mid-flight rule added during running PL/pgSQL function, depth-6 recursion + `EXCEPTION`, mid-flight `rule_gen` bump with active replacement holder (all `active_count == 0`) 7. Wire Extended Query Protocol (`PQexecParams`) & `PREPARE`/`EXECUTE` cached generic plan interception across PG 14–18 8. GCRA QPS rate limiting (burst, cap, elapsed-time admission bounds, phase-2 delta, combined concurrency rollback `active_count == 0`) 9. Restart & immediate-crash persistence, `status.persisted` failure/retry + crash verification, atomic FIFO replacement, startup orphan `.tmp.*` cleanup, lowered `max_rules` preservation until `clear_rules()`, concurrent mutator convergence, and CRC32C-corrupt/truncated fail-open recovery (preserving corrupt disk files across no-op calls) 10. Read-only hot standby (`pg_basebackup` seed identity + live WAL streaming over Unix sockets + local standby `trip()` isolated from primary + standby restart persistence) 11. `pg_stat_statements` bidirectional co-loading (`'pg_stat_statements,pgbreaker'` and `'pgbreaker,pg_stat_statements'`): bit-for-bit `queryid` parity, concurrency & `trip()` enforcement, accurate `pg_stat_statements.calls` accounting, and `0` slot leaks ### Micro-Benchmark (`pgbench`) Measured on PostgreSQL 16.16 (Rocky Linux 9.8 x86_64) via `pgbench -S -M prepared -c 8 -j 4 -T 10` as a non-superuser (2 s warmup + 10 s timed): | Scenario | Throughput (TPS) | Avg Latency | Observed Delta | | :--- | ---: | ---: | ---: | | Vanilla PostgreSQL (`compute_query_id = on`) | 134,252.0 | 0.060 ms | baseline | | `pgbreaker` loaded, 0 rules (fast-path) | 138,676.8 | 0.058 ms | +3.30% | | `pgbreaker` loaded, 100 non-matching rules | 139,701.6 | 0.057 ms | +4.06% | | `pgbreaker` loaded, 100 rules + 1 matching concurrency rule (1,718,920 warmup+timed hits, 0 leaks) | 143,981.5 | 0.056 ms | +7.25% | | `pgbreaker` loaded, 100 rules + 1 matching GCRA QPS rule (1,640,730 warmup+timed hits) | 136,597.0 | 0.059 ms | +1.75% | On this single-host 10-second run (~134k–144k TPS), observed throughput across loaded scenarios ranged from +1.75% to +7.25% relative to vanilla PostgreSQL, with `0` leaked slots across all matched executions.