pg_mooncake
AGENTS.md2k starsChanged 13 months agoMITView on GitHub
The contributor guide: the invariants a change must keep, where things live, how to build and test, and common pitfalls. The architecture and the wire format are described in docs/ARCHITECTURE.md, and the tests in TESTING.md. Statements tagged [pins] hold at the submodule pins listed at the top of docs/ARCHITECTURE.md. Re-verify them whenever a submodule pin moves. Users get duckdb_mooncake as a prebuilt binary: CREATE EXTENSION runs duckdb.install_extension('mooncake', 'community') (src/sql/bootstrap.sql). That binary was built against moonlink_rpc at the commit locked in…
- Deletes or force-pushes
- Installs packages
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 33,398 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repositoryOne other file it gives its agents.
- CLAUDE.mdCLAUDE.md
The file
We split this AGENTS.md into the rules it gives an agent
8 rules. About 0 are common, 1 is distinctive, and 7 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈1
Distinctive · estimate
This author's own choices. Worth a look.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 15
No version is negotiated at runtime, so anything below that changes breaks every user on the default install, even when your local tests …
- Very specific: line 75
If DropTable fails (moonlink down, erroring, or silent), the DROP still commits and emits a WARNING per mirror.
- Very specific: line 76
All drops of a transaction share one 30 s deadline, and once moonlink is unreachable the remaining ones are not attempted.
- Very specific: line 87
Never .expect()/.unwrap() an RPC result.
- Very specific: line 134
Add this to the cluster's postgresql.conf (pgrx clusters live in ~/.pgrx/data-NN):
- Very specific: line 185
Call moonlink with rpc!(moonlink_rpc::<fn>, args..).unwrap_or_else(|e| error!("mooncake.x failed: {e}")).
- Very specific: line 186
Use only existing RPCs (section 1: the wire format must not change).
- Very specific: line 190
Add a regress test (pitfall 6) and run make test for every supported major.
≈ “Common” is an estimate: at least 1 in 5 of the 43,423 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Contributing to pg_mooncake
The contributor guide: the invariants a change must keep, where things live, how to build and test, and common pitfalls. The architecture and the wire format are described in docs/ARCHITECTURE.md, and the tests in TESTING.md.
Statements tagged [pins] hold at the submodule pins listed at the top of docs/ARCHITECTURE.md. Re-verify them whenever a submodule pin moves.
1. Contract with duckdb_mooncake: never change these
Users get duckdb_mooncake as a prebuilt binary: CREATE EXTENSION runs
duckdb.install_extension('mooncake', 'community') (src/sql/bootstrap.sql). That binary was built against
moonlink_rpc at the commit locked in duckdb_mooncake/moonlink_ffi/Cargo.lock (git dependency on the moonlink repo).
No version is negotiated at runtime, so anything below that changes breaks every user on the default install, even
when your local tests (with a locally built extension) pass.
- Do not change the wire format (described in docs/ARCHITECTURE.md). The
rpcs!{}list inmoonlink/src/moonlink_rpcdefines it: bincodeconfig::standard(), where the enum variant index is encoded, so order matters. The list happens to be alphabetical, so adding a variant "in order" silently renumbers the ones after it. - Framing (
moonlink_rpc/src/lib.rswrite/read): u32 native-endian length prefix, then the bincode payload. - Responses are
RpcResult<T> = Result<T, moonlink_error::ErrorStruct>. Do not changeErrorStruct(moonlink/src/moonlink_error/src/error.rs:message,status: ErrorStatus,sourcewith custom serde,location) orErrorStatus. The prebuilt binary decodes every error reply through them. GetTableSchemareturns an Arrow IPC stream with only the schema (arrow_ipc::writer::StreamWriterinmoonlink_service/src/rpc_server.rs), which duckdb_mooncake decodes with nanoarrow.ScanTableBeginpayload (moonlink/src/moonlink_table_metadata/src/table_metadata.rsEncode): u32 native-endian arrays thatduckdb_mooncake/src/storage/mooncake_table_metadata.cppreinterprets in place. Puffin deletion-vector blobs are read as portable CRoaring atoffset+20, lengthsize-24. Every file named in the payload must stay readable untilScanTableEnd.- C symbols that duckdb_mooncake
dlsyms frompg_mooncake.so(duckdb_mooncake/src/include/pgmooncake.hpp):pgmooncake_get_init_query,pgmooncake_get_lsn,pgmooncake_drop_cstring(src/duckdb_mooncake.rs).pgmooncake_drop_cstringhas no Rust caller, but it is not dead code: removing it makes the extension call a NULL function pointer. - ATTACH string and naming:
ATTACH DATABASE 'mooncake' (TYPE mooncake, URI '<mooncake.data_directory>/moonlink.sock', DATABASE '<db>')(pgmooncake_get_init_query). With a relativemooncake.data_directory, such as the defaultpg_mooncake, the socket path is relative to the backend's cwd ($PGDATA). Tables are addressed as unquotedschema.table(format!("{}.{}", schema, table)induckdb_mooncake/moonlink_ffi/src/lib.rs), so pg_mooncake must register mirrors with moonlink under that exact string.
2. Other invariants
- The moonlink background worker must not panic or error out. [pins] Restart behavior:
- A panic in a per-table handler puts that mirror into the errored state (a fallback loop keeps answering for it and
still performs its DROP); other mirrors keep replicating. A panic in a per-connection RPC handler surfaces as
early eofon that connection. - A mirror that fails recovery at startup is errored (a transient failure is retried) instead of failing the worker.
- An error or panic on the main path exits with status 1 and the worker restarts after 15 s
(
src/bgworker.rsunwrapsstart_with_config's result on the main thread). - moonlink returns only after SIGTERM. During a server shutdown (
stoppinginpostmaster.pid) the worker exits with status 0. Any other SIGTERM (akillof the worker;pg_terminate_backendcan't reach it, since it has no database connection) exits with status 1, so Postgres restarts it after 15 s. Keep shutdowns at status 0: the e2e gate's stop checks count abnormal worker exits.
- A panic in a per-table handler puts that mirror into the errored state (a fallback loop keeps answering for it and
still performs its DROP); other mirrors keep replicating. A panic in a per-connection RPC handler surfaces as
- Shutdown signals are handled only on the worker's main thread (
src/bgworker.rs). moonlink'stokio::signalhandler chains to pgrx's SIGTERM handler, which calls into Postgres and panics on any other thread, so SIGTERM, SIGHUP and SIGINT are blocked in every moonlink thread: the main thread blocks them while it creates the runtime and themoonlinkthread (which inherit its mask),on_thread_startcovers threads created later, and the main thread then restores its own mask and only waits. Keep that if you change how the runtime is built, and don't call Postgres from moonlink threads. ServiceConfigis built with a struct literal insrc/bgworker.rs. Adding or removing a field inmoonlink_serviceneeds a matching edit there. [pins]- On this path moonlink uses only the sqlite metadata store (
<mooncake.data_directory>/moonlink_metadata_store.sqlite, the recovery source of truth) and the filesystem Iceberg catalog. It keeps no write-ahead log: the replication slot is acknowledged only up to what every healthy mirror has persisted to Iceberg, and the rest is replayed from the slot after a restart (docs/ARCHITECTURE.md, "Consistency model"). [pins] - User-level recovery is "drop and re-create the mirror" (
DROP TABLE <mirror>; CALL mooncake.create_table(...)). DROP must succeed no matter what state moonlink is in (the flow: docs/ARCHITECTURE.md, "Processes and data flow", step 6):- An
object_access_hook(src/drop_tracking.rs) records which dropped relations are mooncake mirrors (byrelam, before the catalog rows go away; this covers cascades andDROP SCHEMA). Thesql_droptrigger queues those, and a pre-commit transaction callback sendsDropTablefor each one that is still gone at top-level commit, so a drop undone byROLLBACK TO SAVEPOINTor an exception block keeps the mirror.PREPARE TRANSACTIONafter dropping a mirror is an error. Dropping any other table never talks to moonlink. - If
DropTablefails (moonlink down, erroring, or silent), the DROP still commits and emits a WARNING per mirror. All drops of a transaction share one 30 s deadline, and once moonlink is unreachable the remaining ones are not attempted. moonlink may then still hold the mirror (it shows up inmooncake.list_tables()). - moonlink also keeps a mirror whose table was dropped without the
sql_droptrigger firing: byDROP EXTENSION pg_mooncake CASCADE(the trigger is dropped by the same command) or withsession_replication_role = replica(event triggers don't fire).mooncake.create_tabletherefore drops whatever moonlink holds under the new mirror's name before registering it (the name was free in Postgres, so that table is an orphan), and drops the new Postgres table again if moonlink refuses it. So re-creating a mirror cleans up its orphan; to clean one up without re-creating:CREATE TABLE <same name> (id int) USING mooncake; DROP TABLE <same name>;. - RPC errors become normal Postgres ERRORs raised after the connection lock is released (
rpc!insrc/utils.rs). The lock is poison-tolerant. A connection that saw an IO or decode error is discarded, and a cached connection is probed (MSG_PEEK) before reuse, so the first call after a moonlink restart reconnects instead of failing. Never.expect()/.unwrap()an RPC result.
- An
3. Components and where things live
| Path | Language | Role |
src/ | Rust (pgrx 0.16.1) | The extension: mooncake.* SQL API, mooncake table AM, the moonlink background worker |
moonlink/ (submodule) | Rust | Ingestion engine inside the worker: CDC from a logical slot, Iceberg writer, Unix-socket RPC server |
pg_duckdb/ (submodule) | C++ | Embeds DuckDB in each backend. Routes queries on USING mooncake tables to DuckDB |
duckdb_mooncake/ (submodule) | C++ + Rust FFI | DuckDB extension mooncake: gets a snapshot from moonlink, then reads the parquet/puffin files directly |
| What | Where |
_PG_init, bootstrap SQL | src/lib.rs, src/sql/bootstrap.sql |
mooncake.create_table/create_snapshot/optimize_table/list_tables, drop event trigger, identifier parsing | src/functions.rs |
Which dropped relations are mirrors (object_access_hook) | src/drop_tracking.rs |
Rejecting writes, renames and attaching on mirrors (planner_hook and ProcessUtility_hook, run before pg_duckdb's) | src/mirror_writes.rs |
mooncake table AM (mostly unimplemented!()) and its registration with pg_duckdb | src/table.rs |
Background worker (ServiceConfig, start_with_config) | src/bgworker.rs |
Per-backend RPC connection (rpc!), tokio runtime, DATABASE | src/utils.rs |
| C symbols for duckdb_mooncake | src/duckdb_mooncake.rs |
| RPC definitions and framing / server / service startup | moonlink/src/moonlink_rpc/src/lib.rs, moonlink/src/moonlink_service/src/{rpc_server.rs,lib.rs} |
Backend API, table_config JSON, recovery | moonlink/src/moonlink_backend/src/{lib.rs,table_config.rs,config_utils.rs,recovery_utils.rs} |
| Postgres CDC (slot, publication, confirmed-LSN feedback) | moonlink/src/moonlink_connectors/src/pg_replicate*.rs, pg_replicate/ |
| Table engine, Iceberg, union read, errored state [pins] | moonlink/src/moonlink/src/{table_handler.rs,storage/,union_read/} |
DuckDB side: catalog, scan, payload decoding, dlsyms, RPC client | duckdb_mooncake/src/storage/*.cpp, src/include/pgmooncake.hpp, src/moonlink/moonlink.cpp, moonlink_ffi/src/lib.rs |
| Regression tests | tests/pg_regress/{sql,expected} |
4. Setup, build, test (standard toolchain)
The checks are make test (pg_regress) and the end-to-end gate scripts/e2e-smoke.sh, which covers what pg_regress
cannot: moonlink down or hung, restarts, crashes, DDL and TRUNCATE on sources. See TESTING.md for both and for CI
(.github/workflows/ci.yml: make test on PostgreSQL 14-18 for pull requests, plus the gate on PostgreSQL 17 and 18 for
pushes). Run the gate yourself before changing the worker, the RPC client or DROP handling.
git clone --recurse-submodules https://github.com/Mooncake-Labs/pg_mooncake.git && cd pg_mooncake
# Rust: rustup picks up rust-toolchain.toml (1.88.0, clippy, rustfmt). pgrx needs rustfmt at build time.
cargo install --locked cargo-pgrx@0.16.1
cargo pgrx init --pg17 download --pg18 download # or --pgNN "$(which pg_config)" for an existing installBuild and install for one PG major (repeat with pg17):
export PG_VERSION=pg18
make pg_duckdb PG_VERSION=$PG_VERSION # pg_duckdb + libduckdb into that PG
make install PG_VERSION=$PG_VERSION # release build; PG_CONFIG=<pg_config> installs into another PGAdd this to the cluster's postgresql.conf (pgrx clusters live in ~/.pgrx/data-NN):
shared_preload_libraries = 'pg_duckdb,pg_mooncake' # this order: pg_mooncake needs pg_duckdb's symbols
wal_level = logical
duckdb.allow_community_extensions = trueTests:
make test PG_VERSION=pg18 # cargo pgrx regress against ~/.pgrx/data-18; PATH does not matter here
make test PG_VERSION=pg17
cargo pgrx run pg18 # interactive psql on the pgrx cluster (`make run` = pg_duckdb + this, PG18)make test installs a debug build of pg_mooncake. Reinstall with make install before measuring performance.
Using a locally built duckdb_mooncake
Needed only when you change duckdb_mooncake/. Build it with make duckdb_mooncake. CRoaring ≥ 1.x must be findable by
CMake: the devcontainer uses vcpkg via VCPKG_TOOLCHAIN_PATH, and distro packages such as Ubuntu 24.04's
libroaring-dev 0.2.66 are too old. Corrosion and nanoarrow are fetched by CMake. Then copy
duckdb_mooncake/build/release/extension/mooncake/mooncake.duckdb_extension into
<duckdb.extension_directory>/v1.4.1/linux_amd64/ without a .info file, which makes the bootstrap INSTALL a no-op,
and set duckdb.allow_unsigned_extensions = true and duckdb.autoinstall_known_extensions = false. Both DuckDB trees
(pg_duckdb/third_party/duckdb, duckdb_mooncake/duckdb) must be the same version (v1.4.1).
5. Pitfalls
cargo pgrx installwithout--pg-configuses the firstpg_configonPATH. With another Postgres onPATHit compiles for the right major but installs into the wrong prefix.make installandmake packagepass--pg-config "$PG_CONFIG"; callcargo pgrx installdirectly only with--pg-config.- The
bgworkercargo feature (default) is what starts moonlink. A--no-default-featuresbuild has no worker, and every call fails withmooncake.<procedure> failed: failed to connect to moonlink: .... mooncake.create_tablecreates the mirror table on a separate, autocommitted libpq connection (loopback by default, orsrc_uri). It is not part of the caller's transaction, so aROLLBACKdoes not undo a create_table that returned. If theCreateTableRPC fails, create_table drops the new table again on that connection.- Replication connections are keyed by
src_uri(moonlink_connectors/src/replication_manager.rs). The slotmoonlink_slot_<db>and publicationmoonlink_pubare dropped when the last mirror of thatsrc_uriis dropped. - No committed
Cargo.lock(/Cargo.lockis gitignored): the moonlink dependency graph resolves fresh.postgres/postgres-native-tlsare pinned to the rust-postgres revision moonlink uses (make check-rust-postgreschecks it)..cargo/config.tomlmakes the resolver prefer versions that supportrust-versioninCargo.toml; keep that equal to therust-toolchain.tomlchannel, or a fresh resolution picks crates the pinned compiler cannot build. - New regress test without an expected file:
cargo pgrx regressprompts "Accept [Y, n]?" and panics without a terminal.--autoaccepts new output and overwrites failing expected files. Prefer: create an emptyexpected/<name>.out, runmake test, reviewtests/pg_regress/results/<name>.out, then copy it. Diffs land intests/pg_regress/regression.diffs.
6. Recipe: adding a mooncake.* procedure
- In
src/functions.rs, follow the existing pattern:#[pg_extern(sql = "CREATE PROCEDURE mooncake.x(...) LANGUAGE c AS 'MODULE_PATHNAME', '@FUNCTION_NAME@';")]. Parse table arguments withparse_table(Postgres identifier rules). SendTableName::moonlink_name()(unquotedschema.table) over RPC; useTableName::quoted()only in SQL you run yourself. Call moonlink withrpc!(moonlink_rpc::<fn>, args..).unwrap_or_else(|e| error!("mooncake.x failed: {e}")). - Use only existing RPCs (section 1: the wire format must not change). A feature that needs a new RPC is a
coordinated moonlink + duckdb_mooncake release, not a pg_mooncake change. If you do touch moonlink, the change has to
land in the moonlink repo and the submodule pin has to move. An exhaustive
matchinrpc_server.rs::handle_streamand aMoonlinkBackendmethod go with every RPC. - Add a regress test (pitfall 6) and run
make testfor every supported major.
7. Known limitations
The user-visible limitations are listed once, in CHANGELOG.md. Fix them with a test;
don't paper over them. The end-to-end gate's expected failures and their failure signatures are in
scripts/e2e-known-bugs.txt (TESTING.md).
8. Conventions
- Rust:
make format(cargo fmt+cargo clippy). duckdb_mooncake C++:make -C duckdb_mooncake format-all. - Reads from another session are eventually consistent (about 0.5 s locally). Only the writing session gets
read-your-writes (a scan waits for that backend's
XactLastCommitEnd). Tests must poll, or read in the writing session.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

