matejformanek
UserTurn Claude Code into a long-term collaborator on PostgreSQL internals — cited knowledge corpus, agent skills, slash commands, and task-shaped scenarios for backend hacking.
Categories
Indexed Skills (41)
pg-feature-plan
Drop a heavy, citation-rich implementation plan for a scoped PostgreSQL backend feature — Phase 2 of the two-phase PG planner, the bridge from a brainstorm-with-picked-approach to /pg-implement. Names every src/backend or src/include file that must change with file:line cites at a pinned anchor, enumerates catalog / CATALOG_VERSION_NO / WAL / on-disk / lock-order / extension-ABI risks, proposes the test surface (regress / iso / TAP), structures the patch into independently-reviewable phases, picks a CommitFest landing strategy, and emits the plan-mode plan that /pg-implement executes phase-by-phase with plan-linked commits. **Use proactively whenever the user invokes /pg-plan, says "plan this PG feature", "make a plan for X in PG", "drop a heavy plan", "plan-mode plan for [PG feature]", "i picked option [A/B/C] in the brainstorm, now plan it", "we settled on the [approach] for the [PG topic], write me the phase plan with file:line cites", "spec-to-plan this pgsql-hackers thread", "shadow-implementation plan a
access-method-apis
Implement or modify a PostgreSQL pluggable index AM or table AM — covers IndexAmRoutine callbacks (ambuild, aminsert, amgettuple, amgetbitmap, ambulkdelete, amvacuumcleanup, amparallelrescan), TableAmRoutine callbacks (scan_begin, scan_getnextslot, tuple_insert, tuple_insert_speculative, slot_callbacks, index_fetch_*), opclass / strategy numbers / support functions, TID semantics for non-heap stores, genam.c and tableam.h wrappers, plus CREATE ACCESS METHOD + pg_am / pg_opclass / pg_amproc / pg_amop catalog registration. Use whenever a PG patch implements or modifies an index AM (btree variant, hash, gin, gist, spgist, brin, custom) or a table AM (heap, columnar, in-memory, custom store), or designs TID semantics for a non-heap storage. Skip user-facing "which index type should I use" / "should this be a btree or hash index" advice, EXPLAIN tuning questions, GIN / GIST / btree CONCURRENTLY operational guidance, application-side ORM index hints, and non-PG storage engines (MySQL InnoDB / MyRocks, RocksDB, Leve
aio-readstream
PostgreSQL's async I/O subsystem + the read-stream API — `src/backend/storage/aio/` (introduced PG 17, matured PG 18). Loads when the user asks about the read_stream API, AIO methods (sync / worker / io_uring), how sequential + bitmap scans issue prefetch, migrating a code path from `StartReadBuffer`+`WaitReadBuffer` to `read_stream_*`, adding a new read-stream consumer, tuning `io_max_concurrency` / `io_workers` / `io_method`, or debugging AIO-related buildfarm failures. Also for the read-stream callbacks (per-block-lookup / per-buffer-release), completion callbacks (`aio_callback.c`), and the io_uring linkage. Skip when the ask is about client-side async (libpq) or about the WAL writer / walreceiver (those have their own I/O paths).
backup-and-recovery
PostgreSQL's backup + point-in-time recovery — `pg_basebackup` + WAL archiving (archive_command / archive_library) + `restore_command` + `pg_wal_replay_*` targets + the pg_backup_start/stop API + `pg_receivewal`. Covers `src/backend/backup/` (basebackup server code) + `src/backend/postmaster/pgarch.c` (archiver aux process) + `src/backend/access/transam/xlogrecovery.c` (recovery driver). Loads when the user asks about how base backups work, WAL archiving vs streaming replication, PITR targets (`recovery_target_*`), `pg_backup_start`/`pg_backup_stop` low-level API, `.backup` files, restore_command semantics, or incremental backup (PG 17+ with `WAL_SUMMARIZED`). Skip when the ask is about `pg_dump` (logical dump — different tool) or about physical replication streaming (`physical-replication` — related but sibling).
bgworker-and-extensions
Register a PostgreSQL background worker or layer extension hooks on _PG_init — covers RegisterBackgroundWorker (static at shared_preload_libraries time) vs RegisterDynamicBackgroundWorker (runtime), the BackgroundWorker struct (bgw_flags BGWORKER_SHMEM_ACCESS / BGWORKER_BACKEND_DATABASE_CONNECTION, bgw_start_time, bgw_restart_time, bgw_main_arg, bgw_notify_pid), BackgroundWorkerInitializeConnection, the signal handler skeleton (SignalHandlerForConfigReload + die), the WaitLatch idiom with WL_EXIT_ON_PM_DEATH, and the GetBackgroundWorkerPid / WaitForBackgroundWorkerStartup / TerminateBackgroundWorker lifecycle calls. Use whenever a PG patch or extension registers a bgworker, writes a worker_main function, debugs a worker that fails to start or restart, layers ProcessUtility_hook / planner_hook / ExecutorStart_hook on _PG_init, or coordinates bgw_notify_pid signaling. Skip for Celery / Sidekiq / RQ / Resque / Kafka-consumer worker pools, AWS Lambda / Cloud Run background jobs, Cron / systemd timers, OS-level da
build-and-run
Build, install, initdb, and start PostgreSQL from source in the `dev/` clone for backend hacking — covers meson setup (PG ≥ 16 default) with cassert + debug flags, the autoconf ./configure fallback, ninja install, initdb + pg_ctl start / stop, PGDATA / PATH wiring, single-user mode for postmaster startup debugging, attaching gdb / lldb under the per-connection fork model, and -O0 -g3 debug builds. Use whenever a task involves compiling PG from source in dev/, running ninja install on the dev clone, initdb-ing a fresh data directory, starting or stopping the dev cluster via pg_ctl, picking between the debug profile (5432) and ASan profile (5433), or attaching a debugger to a forked backend. Skip for brew / apt / yum / Docker / k8s installation of release PG, Aurora / Cloud SQL / Supabase / Neon-managed PG provisioning, generic CMake / make / Bazel build questions, Linux-kernel builds, Node.js / Python / Go application builds, and pgAdmin / DBeaver client installation.
catalog-conventions
Add or modify a PostgreSQL system-catalog entry — covers adding a pg_proc.dat builtin function, pg_operator.dat operator, pg_type.dat type, pg_cast.dat cast, pg_opclass.dat opclass, adding a new column on pg_class / pg_aggregate / pg_attribute / etc., BKI bootstrap entries, OID assignment policy (genbki.pl, unused_oids), catversion (CATALOG_VERSION_NO) bumping, and regenerating postgres.bki. Use whenever a PG patch edits anything under src/include/catalog/ (.h or .dat), adds a SQL-visible builtin (function/operator/type/cast/opclass), assigns or recycles an OID, or bumps the catversion. Skip for user-level information_schema queries on a running server, Django / Alembic / Rails / Flyway / Liquibase migrations, Oracle DBA_* / MySQL information_schema / Snowflake INFORMATION_SCHEMA catalog questions, schema design and normalization advice, ER-diagram tooling, and adding constraints to user-application tables.
coding-style
Format C code to upstream PostgreSQL house style for src/backend / src/include — covers hard tabs at width 4, BSD braces, postgres.h-first include order, C99 subset rules (no // comments, no VLA, no mid-block declarations), naming conventions (struct typedef + field naming, function names matching typedef names), function-header comment format, ~78-char line length, and pgindent expectations. Use whenever a PG patch edits, adds, or reviews .c / .h files under source/src/ or dev/src/, or when a reviewer flags pgindent churn on a posted patch. Skip for Linux-kernel style (CodingStyle), clang-format / rustfmt / prettier / black / shfmt configurations, non-PG C / C++ style (Google style, LLVM style, Mozilla style), Java checkstyle, JavaScript ESLint, EditorConfig tuning, and general "what's a good C style" advice.
collation-provider
PostgreSQL's collation-provider abstraction — the 3-way split between `builtin` (PG-owned), `icu` (ICU library), and `libc` (OS-provided). Covers `src/backend/utils/adt/pg_locale.c` (the dispatcher) + `pg_locale_builtin.c` / `pg_locale_icu.c` / `pg_locale_libc.c` (per-provider implementations) plus the encoding conversion layer (`src/backend/utils/mb/`). Loads when the user asks about `CREATE COLLATION`, provider semantics, `LC_COLLATE` / `LC_CTYPE`, ICU integration + version tracking, the `builtin` provider added PG 17, `collversion` upgrade detection, why an ORDER BY differs between PGs on the same OS, `pg_c_utf8` builtin, or multibyte encoding conversion. Skip when the ask is about client encoding (server-client convert is included but psql `\encoding` is client-side), full-text search dictionaries (different subsystem `tsearch`), or `CREATE TEXT SEARCH CONFIGURATION`.
copy-family
Understand and modify the COPY FROM / COPY TO family in PostgreSQL — `src/backend/commands/copy*.c`. Loads when the user asks about COPY-command internals, bulk-load performance, custom COPY formats, extending COPY options, COPY error-handling / ON_ERROR, COPY progress reporting, tablesync (which is built on COPY), or any patch touching `copy.c` / `copyfrom.c` / `copyfromparse.c` / `copyto.c`. Also use when investigating why COPY behaves differently from INSERT (partition routing, defaults, generated columns, extended statistics, RLS, triggers, DEFAULT expressions), and when adding a new bulk-load code path that reuses the COPY machinery. Skip when the question is about `pg_dump` / `psql \copy` (client-side) or logical-replication apply (different subsystem — but note that tablesync's initial copy IS this machinery, see `knowledge/idioms/tablesync-initial-copy.md`).
corpus-chain
Traverse the pg-claude knowledge graph to answer "what does this feature/file/pattern touch across the corpus?" — pulls scenarios, idioms, call-site file examples, sibling patterns, subsystem ownership, and analogous past features from planning/ + sessions/ into a single chain map. Uses the graph edges built by `scripts/populate-idiom-callsites.py` (idiom → files) and `scripts/build-scenario-idiom-matrix.py` (scenario ↔ idiom bidirectional). Use proactively when brainstorming a new PG feature, planning §3 file table, investigating an unfamiliar subsystem, or trying to find "have we touched something like this before?". Also use inside `pg-feature-brainstorm` step 1 (subsystem framing) and `pg-feature-plan` before §3 to seed the file list from existing evidence rather than pure grep. Skip when you already have the anchor's downstream chain memorized, when the task is a one-file bug fix, or when the ask is about non-PG code.
custom-scan-api
PostgreSQL's Custom Scan / Custom Path API — the pluggable executor node interface that lets extensions add new physical operators (custom joins, custom aggregates, custom scan providers like columnar backends). Covers `CustomScanMethods` + `CustomExecMethods` + `CustomPathMethods` in `src/backend/executor/nodeCustom.c` + `src/backend/optimizer/util/plannodes.c` (for CustomPath / CustomScan). Loads when the user asks about custom scan providers, how citus / timescaledb / greenplum-style columnar backends integrate, CustomPath cost registration, `RegisterCustomScanMethods`, or "how does the planner know about my extension's node type". Skip when the ask is about extending the built-in AM (table AM / index AM — different pluggable interface) or about GetForeignPaths (FDW — sibling but has its own skill).
debugging
Debug a running PostgreSQL backend with lldb / gdb — covers attaching to the right forked backend via pg_backend_pid, single-user mode for postmaster / InitPostgres startup paths, breakpoints in ExecInitNode / heap_update / LWLockAcquire, elog(LOG, ...) printf-debugging, macOS / Linux core-dump configuration, and SQL-level inspection via pg_buffercache / pageinspect / pg_visibility. Use whenever the user wants to step through backend C code, attach lldb / gdb to a specific dev-cluster backend, chase a SIGSEGV / hang / loop / assertion-failure in PG, instrument with elog, inspect shmem / buffer / lock state at runtime, or read a PG core dump. Skip for app-level debugging in Node.js / Python / Ruby / Go / Rust (use language-specific debuggers), JVM hprof / jstack, browser DevTools, Chrome Tracing, application performance profiling, and production PG tuning (autovacuum / shared_buffers — that's DBA work).
error-handling
Write or review a PostgreSQL backend ereport / elog call — covers ereport vs elog, picking a SQLSTATE from errcodes.txt, errcode_for_file_access, errmsg / errdetail / errhint capitalisation rules, soft errors via escontext, PG_TRY / PG_CATCH longjmp-safe cleanup blocks, and the DEBUG / LOG / NOTICE / WARNING / ERROR / FATAL / PANIC elevel ladder. Use whenever a PG patch adds, edits, or reviews C in source/src/backend or contrib/ that reports an error or logs a message — picking elevel, choosing a SQLSTATE, formatting errmsg, wiring PG_TRY/PG_CATCH around a longjmp-unsafe block, or migrating a call to soft-error style. Skip for Python try/except, Go error returns, Rust Result / anyhow / thiserror, C++ exceptions, Java checked exceptions, Sentry / pino / Winston / log4j application logging, Oracle ORA-* / MySQL error codes, and general error-handling philosophy questions.
executor-and-planner
Edit the PostgreSQL executor or planner — covers src/backend/executor/ (nodeXxx.c, ExecInitNode/ExecProcNode/ExecEndNode/ExecReScan dispatch, PlanState lifecycle, EXPLAIN wiring) and src/backend/optimizer/ (Path → Plan via createplan.c, RelOptInfo lifecycle, add_path cost-dominance pruning, cost_* units in cost.h). Use whenever a PG patch adds or modifies a plan-node executor, introduces a new Path or Plan type, changes cost-model fields in cost.h, adds EXPLAIN output for a node, plumbs a node into execParallel.c, or tweaks join-path enumeration. Skip for end-user query tuning, EXPLAIN ANALYZE of a production query, work_mem / shared_buffers tuning, MySQL / MongoDB / BigQuery / Snowflake / DuckDB / Spark / Trino query engines, ORM query-builder optimization, and pandas / polars dataframe operations.
extended-statistics
PostgreSQL's extended statistics — `CREATE STATISTICS`, `pg_statistic_ext`, `pg_statistic_ext_data` — the 4 stat kinds (dependencies / ndistinct / mcv / expressions) that help the planner handle correlated columns, multi-column NDVs, and expression cardinality. Covers `src/backend/statistics/extended_stats.c` + `dependencies.c` + `mcv.c` + `mvdistinct.c`. Loads when the user asks about extended stats syntax, when to `CREATE STATISTICS`, why a query has bad estimates on correlated columns, ndistinct for GROUP BY estimation, MCV lists in the extended-stats context, or the planner's `clauselist_selectivity_ext` selectivity path. Skip when the ask is about `pg_statistic` (single-column stats — the sibling; see `analyze-block-and-reservoir-sampling` idiom) or about ANALYZE mechanics (that's `analyze.c` — different code path).
extension-development
Build a PostgreSQL backend loadable extension (.so / contrib module) — covers the .control file, the foo--1.0.sql install script + foo--1.0--1.1.sql upgrade scripts, PGXS vs meson build wiring, the `_PG_init` entry point, shared_preload_libraries vs LOAD vs CREATE EXTENSION load timing, chained hook installation (ProcessUtility_hook, planner_hook, ExecutorStart_hook), trusted vs untrusted extensions, and SQL-callable C function declarations (PG_FUNCTION_INFO_V1, PG_RETURN_*). Use whenever a PG extension is being written or modified — wiring _PG_init, registering hooks, picking PGXS vs meson, writing install/upgrade SQL, declaring CREATE FUNCTION ... LANGUAGE C, or marking the extension trusted. Skip for VS Code / Chrome / Firefox / Safari / browser extensions, NPM / pip / RubyGems / Cargo packages, IntelliJ / Eclipse plugins, and shell completion scripts.
fdw-development
Building or modifying a Foreign Data Wrapper (FDW) — the SQL/MED interface for accessing external data as if it were PG tables. Covers the `FdwRoutine` callback set (`GetForeignRelSize` / `GetForeignPaths` / `GetForeignPlan` / `BeginForeignScan` / `IterateForeignScan` / `ReScanForeignScan` / `EndForeignScan` for scans, `BeginForeignInsert` / `ExecForeignInsert` / … for DML), the `postgres_fdw` reference implementation, plan pushdown (WHERE / JOIN / AGG / LIMIT), extended-explain support, and the FDW-related core code (`src/backend/foreign/foreign.c`, foreign-table catalog, user mappings). Loads when the user asks about writing an FDW, `CREATE FOREIGN TABLE`, why postgres_fdw is fast, pushdown decisions (`use_remote_estimate`, `fdw_startup_cost`), user mappings and password security (`password_required`), the loopback-back-to-self bypass-RLS pattern from postgres_fdw, or adding a new pushdown-shape. Skip when the ask is about specific non-postgres_fdw wrappers (file_fdw, oracle_fdw external, mysql_fdw external
fmgr-and-spi
Write a SQL-callable C function or call PostgreSQL fmgr / SPI from C — covers PG_FUNCTION_INFO_V1, PG_GETARG_* / PG_RETURN_*, PG_ARGISNULL, SRF_* set-returning function ValuePerCall and Materialize modes, composite / polymorphic returns, DirectFunctionCall* / OidFunctionCall* / FunctionCallInvoke fmgr entry points, plus SPI_connect / SPI_execute / SPI_prepare / SPI_finish, plan caching, SPI cursors, subxact rollback, and SPI return codes. Use whenever a PG patch or extension adds a `Datum foo(PG_FUNCTION_ARGS)` entry point, exposes a set-returning function, calls fmgr from backend C, or embeds SQL via SPI in a backend / trigger / PL handler. Skip for plpgsql / PL/Python / PL/Perl user-side function authoring, libpq / psycopg / JDBC / node-postgres client-side query execution, generic executor questions (use executor-and-planner), and non-PG embedded SQL (Oracle OCI, SQLite C API).
free-space-map
PostgreSQL's Free Space Map (FSM) — the tree-of-pages that tracks per-heap-page free space so `INSERT` / `COPY` / `heap_multi_insert` can find a page with room without scanning the whole relation. Covers `src/backend/storage/freespace/` (`freespace.c` + `fsmpage.c` + `indexfsm.c`), the tree layout (leaf-page nodes + 2 upper levels), category encoding (bucketed free-byte counts), the FSM lock discipline, VACUUM's post-scan `FreeSpaceMapVacuum`, and index FSM's simpler use case. Skip when the ask is about visibility map (VM — sibling but different subsystem) or about `pg_freespacemap` contrib module (that's the SQL introspection wrapper).
gucs-config
Add or modify a custom GUC variable in a PostgreSQL backend patch or extension — covers DefineCustomBoolVariable / IntVariable / RealVariable / StringVariable / EnumVariable, picking the right GucContext (PGC_POSTMASTER / PGC_SIGHUP / PGC_SUSET / PGC_USERSET), MarkGUCPrefixReserved, the check/assign/show hook trio, GUC_LIST_INPUT / GUC_LIST_QUOTE / GUC_UNIT_MS / GUC_UNIT_KB / GUC_REPORT / GUC_EXPLAIN flags, and string-GUC guc_malloc rules. Use whenever a PG patch or extension calls DefineCustom*Variable, picks a GucContext, wires check/assign/show hooks, debugs a placeholder GUC, or marks a GUC reserved via MarkGUCPrefixReserved. Skip for DBA tuning of shared_buffers / max_connections / work_mem in production, dotenv / Viper / Dynaconf / Spring @Value configuration libraries, Kubernetes ConfigMap, Terraform variables, and non-PG application config systems.
jsonpath-and-jsonb
PostgreSQL's SQL/JSON support — jsonpath (SQL:2016 path language) + jsonb (binary-encoded JSON) + the SQL/JSON operators like `->`, `->>`, `@?`, `@@`, `jsonb_path_query`. Covers `src/backend/utils/adt/jsonb*.c` (jsonb storage + operators + GIN opclass + subscripting) and `jsonpath*.c` (path language parser + executor). Loads when the user asks about jsonpath semantics, path variables ($, @, current), lax vs strict mode, predicate expressions, `jsonb_path_query` / `jsonb_path_exists`, JSON_TABLE (SQL:2023 / PG 17+), jsonb_gin operator class, memory management in jsonpath_exec (Tom Lane's 5a2043bf713 rewrite), or "why is my JSON search slow" (usually GIN or path complexity). Skip when the ask is about the older `json` type (`json.c` is separate — text representation) or about JSON output formats (that's `format_type` territory).
locking
Pick a PostgreSQL backend lock primitive (atomic / spinlock / LWLock / heavyweight / predicate / buffer-pin-content) or debug a lock-ordering bug, silent LWLock hang, deadlock-detector report, or a multixact / tuple-lock interaction — the six-layer PG lock taxonomy in operational form. Covers `pg_atomic_u32 / u64` ordering + memory barriers, `SpinLockAcquire / SpinLockRelease` (with the "no calls / no ereport / no CHECK_FOR_INTERRUPTS" rules), `LWLockAcquire LW_SHARED / LW_EXCLUSIVE` and tranches (lwlocklist.h + wait_event_names.txt), heavyweight `LockAcquire` / `LockRelationOid` / `LOCKTAG_*`, predicate (SSI) locks, buffer pin / content locks, the `BufferMapping / LockManager / PredicateLockManager` partition rank rules, multi-XID `HEAP_XMAX_IS_MULTI` interaction with `FOR UPDATE / FOR KEY SHARE`, parallel-worker lock-group semantics, and the lldb-attach recipe for silent-LWLock-deadlock diagnosis. **Use this skill proactively whenever the user is writing or reviewing C in `src/backend` or `dev/src/backend`
logical-replication
PostgreSQL's logical replication — publisher-side WAL decoding + subscriber-side apply — plus everything under `src/backend/replication/logical/`. Loads when the user asks about logical decoding, `pg_logical_slot_get_changes`, publications / subscriptions, output plugins (pgoutput / test_decoding), reorder buffer, historic snapshots (SnapBuild), the apply worker + parallel apply, conflict resolution (PG 18+ conflict tracking), replication origins, replication slots (physical vs logical, `slot.c` + `slotsync.c`), streaming mode for in-progress transactions, tablesync's initial COPY, or debugging apply-worker crashes / slot advancement / catalog_xmin retention. Skip when the ask is about physical streaming replication (walsender/walreceiver, `replication/basebackup*.c`, `replication/walsender.c` in isolation) — those are the sibling `replication` subsystem, mostly disjoint code paths.
memory-contexts
Allocate memory in PostgreSQL backend C — pick the right MemoryContext and use palloc / palloc0 / pstrdup / psprintf correctly. Covers CurrentMemoryContext / TopMemoryContext / per-query / per-tuple / ExecutorState context choice, MemoryContextSwitchTo discipline, the OOM-throws-ereport contract (no NULL checks), pfree vs MemoryContextReset vs MemoryContextDelete, the AllocSet vs Slab vs Generation vs Bump context-type cheat sheet, and leak-scoping in long-running backends. Use whenever a PG patch or extension calls palloc / palloc0 / MemoryContextAlloc, creates or switches a MemoryContext, picks AllocSet vs Slab vs Generation vs Bump, or debugs a context-shaped leak. Skip for plain malloc / free / jemalloc / mimalloc / tcmalloc, JVM / Go / .NET GC tuning, Rust Box / Rc / Arc / lifetimes, shared_buffers / work_mem production tuning, valgrind / heaptrack on non-PG programs, and C++ smart pointers.
memory-keeping
Close out a pg-claude session — sync progress/STATE.md, progress/coverage.md, progress/files-examined.md, and append a sessions/ log entry whenever a session produced durable output (a new knowledge/idioms or knowledge/subsystems doc, a [verified-by-code] fact, a discovered gotcha, a file-by-file deep read, or a locked decision from pg-claude-plan.md §14). Use proactively when the user says "wrap up", "close out the session", "sync memory files", "record this gotcha", "we're done for the day", or "log this for next time" — and whenever durable output was just produced. Skip for PG MemoryContext / palloc / pfree internals questions (use memory-contexts), LangChain / LangGraph / LlamaIndex agent memory and vector stores, application memory leaks / valgrind / heaptrack, conversational chat history persistence, finding old Claude sessions (use find-session), and ChatGPT / Claude.ai conversation export.
multixact
PostgreSQL's MultiXact machinery — `src/backend/access/transam/multixact.c` — the multi-transaction ID system that lets a single heap tuple record multiple concurrent lockers (for `SELECT ... FOR SHARE` and `SELECT ... FOR UPDATE` blends) plus the multixact-freeze / wraparound path. Loads when the user asks about MultiXactId semantics, `xmax` interpretation with the `HEAP_XMAX_IS_MULTI` bit, why a tuple can appear to be locked by multiple transactions, tuple-locking modes (`FOR SHARE` / `FOR NO KEY UPDATE` / `FOR KEY SHARE`), the multixact SLRU (`pg_multixact/`), MultiXact member offsets, or the `autovacuum_multixact_freeze_max_age` wraparound path. Skip when the ask is about clog (regular transaction commit status — sibling but different code) or 2PC prepared transactions.
node-infrastructure
PostgreSQL's Node type system — the tagged-union polymorphism used for parser output (Query, RangeTblEntry), planner output (Path, Plan), executor state (PlanState, ExprState), and every intermediate representation. Covers `src/backend/nodes/gen_node_support.pl` (the code generator) + `src/include/nodes/*.h` + the copy/equal/out/read function families + walker/mutator support (`nodeFuncs.c`). Loads when the user asks about `NodeTag`, adding a new Node type (has scenario `add-new-node-type`), `expression_tree_walker` / `expression_tree_mutator`, why grammar changes require regenerating `nodes.h`, the `T_Foo` enum, or `castNode` / `nodeTag` macros. Skip when the ask is about a specific Node (e.g. SeqScan, HashJoin) — those live under executor/optimizer skills.
parallel-query
Add parallel-aware C code in a PostgreSQL backend patch or extension — covers ParallelContext lifecycle (EnterParallelMode / CreateParallelContext / InitializeParallelDSM / LaunchParallelWorkers / WaitForParallelWorkersToFinish / DestroyParallelContext / ExitParallelMode), shm_toc DSM allocation + key lookup, ExecXXXInitializeDSM / ExecXXXInitializeWorker / ExecXXXReInitializeDSM hooks on plan nodes, and parallel-safety markings (pg_proc.proparallel s/r/u; PARALLEL SAFE / RESTRICTED / UNSAFE). Use whenever a PG patch or extension adds parallel-aware code, picks PARALLEL SAFE/RESTRICTED/UNSAFE for a SQL-callable function, extends execParallel.c, plumbs a worker shmem state via shm_toc, or debugs a parallel worker DSM/TOC issue. Skip for DBA tuning of max_parallel_workers GUC, OpenMP / CUDA / pthread / Tokio / Go-goroutine parallelism, JavaScript Promise.all and async-iter parallel fetches, generic worker-pool questions, and ML data-parallel training.
parser-and-nodes
Hack the PostgreSQL parser or add a new Node type — covers scan.l flex tokenizer, gram.y bison grammar, parse_analyze in analyze.c, kwlist.h keywords, and adding/modifying Node types in parsenodes.h / primnodes.h / plannodes.h that flow through copy/equal/out/read funcs auto-generated by gen_node_support.pl. Spans the AST→Query→Plan three-tree pipeline, mutator/walker conventions (expression_tree_walker, query_tree_mutator), the node-type reference table, List/lappend/foreach idioms, and shift-reduce conflict resolution. Use whenever a PG patch edits src/backend/parser/**, edits src/include/nodes/*.h, adds a new SQL keyword to kwlist.h, extends a parse-tree node, writes a tree mutator/walker, or resolves a gram.y shift-reduce conflict. Skip for non-PG parsers (ANTLR, Babel, nom, tree-sitter, LALRPOP, Yacc/Bison on other projects, LLVM IR / Clang AST), JSON / XML / YAML parsing, and executor-node additions (use executor-and-planner instead).
pg-implement
Execute a PostgreSQL `planning/<slug>/plan.md` phase-by-phase under upstream-grade discipline — Phase 3 of the PG planner suite. Per-phase commits, per-phase regress/iso/TAP runs, plan-linked commit messages, and a running notes log; enforces .claude/rules/pg-implement-discipline.md (R1-R12 — every commit references the plan slug + phase number; every code claim has a file:line cite; phase-end check must pass before the next phase starts). Use when the user says "/pg-implement <slug>", "implement the plan", "let's start implementing the X plan", "execute the planning/<slug>/plan.md", or has a finalized planning/<slug>/plan.md ready to execute. Skip for ad-hoc coding without a plan (no phase structure), non-PG implementation (app code, infra, scripts), the generic /implement flow (multi-project, doesn't enforce PG R1-R12 rules), and exploratory hacking where the plan is still being shaped (use pg-feature-plan instead).
pg-patch-review
Run a multi-agent comprehensive review of a PostgreSQL patch (CommitFest entry, GitHub PR, or local .patch file) — orchestrates the mechanical pre-amble (fetch + apply + build + regress / iso / TAP) and then fans out 5 critic sub-agents IN PARALLEL (architecture / invariants critic cross-checking knowledge/subsystems/*.md INV-* tags, breaking-change critic for on-disk / WAL / catalog / extension-ABI, test-coverage critic, style / commit-message critic, reviewer-reflex critic against knowledge/calibration/gap-catalog.md), then synthesizes one PG-house-style review email. Stage 3 verdict supports REJECT-A/B/C grades for design-level rejections. Use when the user says "/pg-review <CF# | PR# | patchfile>", "deep-review this patch", "comprehensive review of CF NNNN", "mailing-grade review of this patch", or "run the 5-critic fan-out on <patch>". Skip for non-PG patch review, self-review-before-mail (use patch-submission), the lightweight 7-phase walk (use review-checklist), generic GitHub PR review (use review-cha
pg-shadow-implement
Shadow-implement a pgsql-hackers thread to calibrate the pg-claude planner suite — read the COVER + discussion only (NOT the attached patch), produce a spec, run pg-feature-brainstorm / pg-feature-plan / pg-implement as-if the user asked for the feature, then fetch the upstream patch, diff against ours, score the gap, and emit comparison.md + skill-gaps.md. This is the "Phase E" calibration loop. Use when the user invokes `/pg-shadow <thread-url>`, says "shadow-implement that thread", "run Phase E against <thread>", "run a shadow against this hackers thread", or names a pgsql-hackers thread + asks how our planner would handle it. Do NOT trigger for real upstream patches we plan to send (use `pg-feature-plan` + `pg-implement` directly), for already-committed threads (re-implementing landed code is meaningless), or for non-PG calibration.
pg-upgrade-internals
PostgreSQL's `pg_upgrade` — the tool that upgrades a data directory in-place from one major version to another without a dump-restore. Covers `src/bin/pg_upgrade/` architecture, the pre-upgrade checks, catalog dump-restore, relfilenode preservation (or rewriting), the two allocation strategies (link vs copy vs clone), and the "check for known upgrade issues" list. Loads when the user asks about pg_upgrade internals, common upgrade failures ("could not connect to source cluster", ERROR at pg_dump extraction, relfilenumber mismatch), --link vs --clone vs --copy tradeoffs, upgrade-blocking features (unlogged tables, sequences, extensions), or extension upgrade paths. Skip when the ask is about major-version release notes semantics (see `wiki-distilled` corpus) or about pg_dump alone.
physical-replication
PostgreSQL's physical streaming replication — walsender (primary side, `replication/walsender.c`) + walreceiver (standby side, `replication/walreceiver.c`) + slots (`replication/slot.c`) + synchronous replication (`syncrep.c`). Covers the streaming protocol variant, hot standby, standby feedback, synchronous commit, WAL sender/receiver state machines, and the physical-slot semantics that differ from logical slots. Loads when the user asks about streaming replication, hot standby, `pg_basebackup`, synchronous_commit levels, walsender/walreceiver state, primary_conninfo, physical replication slots, standby feedback (`hot_standby_feedback`), or `pg_wal_replay_*` recovery-progress functions. Skip when the ask is about logical replication (`replication/logical/`) — sibling but very different code path.
plpgsql-internals
PostgreSQL's PL/pgSQL procedural-language implementation — `src/pl/plpgsql/src/` — the parser (`pl_gram.y` + `pl_scanner.c`), compiler (`pl_comp.c` — turns source text into `PLpgSQL_function` struct), executor (`pl_exec.c` — the interpreter with 268 KB of statement handlers), function/DO/procedure dispatch (`pl_handler.c`), and the trusted-language sandbox boundary. Loads when the user asks about PL/pgSQL semantics not obvious from SQL (nested exceptions, RAISE / GET STACKED DIAGNOSTICS, cursor lifecycle, RECORD variables, EXECUTE dynamic SQL, GET DIAGNOSTICS, transaction control from within a procedure, plan caching for expressions, or the trusted-vs-untrusted distinction), when investigating "why is my PL/pgSQL slower than raw SQL" (typically plan-cache or exception-block reasons), when adding a new PL/pgSQL feature (has scenario `integrate-with-plpgsql`), or when working with PL/pgSQL security (recall from `2026-06-04-a9-plpgsql` session that trusted-PL gate is enforced exactly twice in `pl_handler.c`, EXE
process-lifecycle
PostgreSQL's per-connection multi-process model — postmaster fork, backend startup / initialization / query loop / clean shutdown, auxiliary processes (checkpointer, bgwriter, walwriter, autovacuum launcher, WAL summarizer, pgarch), background workers (bgworker.c registry + parallel/logical-rep workers), signal handling, and the FATAL/ERROR/PANIC hierarchy. Loads when the user asks about how a connection becomes a backend, what runs before the first query, why a query dies mid-flight, how signals + ProcessInterrupts + CHECK_FOR_INTERRUPTS work together, how autovacuum / bgworker workers get scheduled, or when planning a feature that hooks a startup phase / adds a new auxiliary process / touches shutdown ordering. Skip when the question is about client-side (libpq, drivers) or about the SQL-level session properties (that's `tcop` for query dispatch, `gucs-config` for GUCs).
replication-overview
Hack or review PostgreSQL replication internals — covers physical streaming, archive shipping, logical decoding, logical replication PUB/SUB, and synchronous-commit machinery. Names walsender / walreceiver / replication slot / output plugin callbacks plus the relevant GUCs (wal_level, max_wal_senders, max_replication_slots, max_logical_replication_workers, primary_conninfo, primary_slot_name, synchronous_standby_names) and the source files behind each flavor. Use whenever a PG patch touches walsender, walreceiver, replication slots, logical decoding, output plugins, publications/subscriptions, conflict detection, sync replication, failover slots, pg_basebackup, or pg_receivewal — or when picking which mechanism fits a feature design. Skip for MySQL row-based / GTID replication, MongoDB replica sets, Cassandra hinted handoff, Kafka MirrorMaker / Confluent Replicator, Debezium / Flink CDC pipelines, AWS DMS, and Galera / Group Replication.
resource-owners
PostgreSQL's ResourceOwner infrastructure — `src/backend/utils/resowner/resowner.c` — the tree of resource-tracking objects that release buffer pins, catcache refs, tuple descriptors, snapshots, plancache refs, DSM segments etc. automatically on transaction/subtransaction/portal boundaries. Loads when the user asks about `CurrentResourceOwner`, `ResourceOwnerCreate`/`ResourceOwnerRelease`, why a subtransaction cleanup didn't free a resource, the callback-based extension API (PG 17+), adding a new resource kind, or debugging "resource owner leak" WARNINGs. Skip when the ask is about MemoryContexts (parallel infrastructure but different lifecycle — see `memory-contexts`) or about locks (separate — `locking`).
review-checklist
Review a PostgreSQL patch using the wiki's seven-phase checklist — covers Phase 0 reviewer-reflex gates + REJECT-A/B/C grade rubric for design rejections, plus the wiki's Phases 1-7 (apply/build, regress + check-world, pgindent, design fit, docs, comments, committer-readiness). Applies to reviewing someone else's pgsql-hackers / CommitFest submission OR self-reviewing your own patch before mailing it. Use whenever the user says "review this patch", "is it ready to send to hackers", "CF entry NNNN review", "pre-submission review", "REJECT this patch", or pastes a pgsql-hackers thread asking for a structured review. Skip for generic GitHub PR code review (app code), Terraform / Helm chart review, Python / Ruby / Rust / Go application code review, security audit (use security-review), API design review on REST / GraphQL endpoints, and documentation-only review for non-PG projects.
row-level-security
PostgreSQL's Row-Level Security (RLS) — `CREATE POLICY` / `ALTER TABLE ... ENABLE ROW LEVEL SECURITY` / policy application in the rewriter — plus the related security-barrier machinery + leakproof qualification checks. Loads when the user asks about RLS policy semantics (USING vs WITH CHECK, PERMISSIVE vs RESTRICTIVE), how policies are applied to a query at rewrite time, why a qual can/cannot be pushed below a security barrier, the leakproof function attribute, ROLE mapping for BYPASSRLS / NOFORCERLS, `row_security` GUC, or debugging why an RLS policy is/isn't firing. Also covers security-barrier views (`WITH (security_barrier = true)`), which use the same qual-pushdown-prohibition machinery. Skip when the ask is about pg_hba.conf-level authentication, GRANT/REVOKE table-level privileges, SELinux (`sepgsql`), or database-level security features unrelated to per-row visibility.
Bio shown is the top-scored skill's repo description as a fallback — real GitHub bios land in a future update.