PostgreSQL wire protocol implementation

This page describes how SynergyDB implements the PostgreSQL frontend/backend protocol version 3. It is the implementation reference. Scores, connection examples, known gaps and how to re-run the proofs are on the operator page, PostgreSQL. Authentication policy across all wires is in Security, and config keys are in the Configuration reference.

Code lives in src/protocol/postgres/:

File Role
mod.rs PostgresHandler: listener, startup, SSL negotiation, authentication, the message loop, simple query, error mapping
extended.rs ExtendedQueryHandler: Parse, Bind, Describe, Execute, Close, Sync, Flush; binary result encoding
copy.rs CopyCommand, CopyHandler: the COPY sub-protocol
notifications.rs NotificationRegistry: LISTEN, UNLISTEN, NOTIFY, pg_notify()
catalog.rs, catalog/pg_dump.rs SystemCatalog: answers for pg_catalog, information_schema and introspection functions; the queries pg_dump sends
auth.rs PostgresAuthenticator and PostgresAuthConfig (see "Code that is not wired" below)

Shared pieces: src/protocol/tls.rs (TLS), src/auth/scram.rs (SCRAM-SHA-256 server side), src/auth/wire_auth.rs (failed-login delay), src/protocol/buffer_limits.rs and src/protocol/timeout.rs (limits).

1. Listener and connection lifecycle

The server starts the handler when server.postgres_port is set (default 5432). If [tls] resolves to a certificate, it builds the handler with PostgresHandler::with_tls, otherwise with_storage. It then installs the audit logger when [audit] is on and, in cluster mode, the recovery read gate. Before spawning the handler task, Server::start_handler binds the port once with a blocking TcpListener so a port clash fails startup. (source: src/server/mod.rs, Server::start_handler and the PostgreSQL block of server start-up)

ProtocolHandler::start accepts in a tokio::select! loop with the shutdown channel. Each accepted socket goes one of two ways (source: src/protocol/postgres/mod.rs, PostgresHandler::start, thread_per_connection, spawn_connection_thread):

  • Thread per connection (default). The socket is detached from the shared runtime and handed to a new OS thread named pg-<peer port> with an 8 MiB stack, which runs a single-threaded tokio runtime that drives only this session. Turn it off with SYNERGYDB_PG_THREAD_PER_CONN=0 (or false).
  • Shared runtime. With the variable off, the session is a tokio::spawned task on the main multi-thread runtime.

Both paths wrap the session in crate::auth::audit::in_connection("postgres", ...) so audit records carry the peer address.

On the shared runtime, each statement runs through PostgresHandler::run_engine. Reads that cannot block (a plain SELECT, SHOW or EXPLAIN under 16 KiB without FOR UPDATE/FOR SHARE/FOR NO KEY/FOR KEY SHARE, pg_sleep or pg_advisory) run inline on the worker, up to SYNERGYDB_INLINE_LIMIT concurrent inline statements (default 32). Everything else uses tokio::task::block_in_place. SYNERGYDB_INLINE_EXEC selects the policy: reads (default), all, or none. On a current-thread runtime (the thread-per-connection path) the call runs directly. (source: src/protocol/postgres/mod.rs, run_engine, statement_cannot_block)

Per connection, handle_connection:

  1. Sets TCP_NODELAY.
  2. Reads the first packet with TimeoutConfig::read_timeout (default 60 s). Fewer than 8 bytes is a protocol error.
  3. Handles SSL negotiation (section 2).
  4. Calls handle_session, which wraps the socket in a 64 KiB BufReader and a 64 KiB BufWriter. Output is flushed only when the read buffer is empty (the next read would wait for the client), after an error, and around authentication. This is what lets pipelined extended-protocol batches go out in one write.

When the message loop ends, for any reason, cleanup always runs: the connection is removed from every LISTEN channel, an open transaction is aborted (releasing its row locks), session temporary tables are dropped, and session advisory locks are released. (source: src/protocol/postgres/mod.rs, handle_session, the code after the message loop)

Connection state (ConnectionState in src/protocol/mod.rs) moves New → Authenticating → Ready, then between Ready, InTransaction and Failed, and ends at Closed. The ReadyForQuery status byte is derived from it: I for Ready, T for InTransaction, E for Failed.

SYNERGY_PG_TRACE (any value) prints each simple query, Parse, Bind and Execute result summary to stderr. (source: src/protocol/postgres/mod.rs, pg_trace_enabled)

2. SSL/TLS negotiation

handle_connection reads the protocol version word from the first packet (source: src/protocol/postgres/mod.rs, handle_connection):

First packet code Meaning Behaviour
80877103 SSLRequest With TLS configured: write S, run the rustls handshake (TlsListener::accept), then read the real StartupMessage on the TLS stream. Without TLS: write N and read the StartupMessage in plaintext.
196608 (3.0) StartupMessage Proceed to authentication.
80877102 CancelRequest Exempt from the require_tls check, then treated like any other first packet (see below).
80877104 GSSENCRequest No special case.

With [tls] require_tls = true, a plaintext StartupMessage from a non-loopback peer is answered with ErrorResponse severity FATAL, SQLSTATE 28000, message no encryption: connection from "<ip>" refused, this server requires SSL (sslmode=require), and the connection closes. Loopback peers may still connect in plaintext (source: src/protocol/tls.rs, plaintext_allowed).

TLS is rustls via tokio-rustls. Certificates and key come from PEM files; client-certificate verification (mTLS) uses WebPkiClientVerifier with the configured CA and requires ca_cert_path. (source: src/protocol/tls.rs, build_server_config, resolve_tls_config)

Not wired: cancel requests. There is no CancelRequest handler. A CancelRequest packet is passed to handle_session as if it were a StartupMessage, so no running query is cancelled. The BackendKeyData secret is random per connection and is never checked. No test was found. (source: src/protocol/postgres/mod.rs, handle_connection, handle_session)

Not wired: GSSAPI encryption. A GSSENCRequest is not answered with N; clients that try GSS first (libpq with gssencmode=prefer and a Kerberos ticket) are not handled specially. No test was found.

Not wired: TlsConfig::min_version. The field exists but build_server_config uses rustls' default protocol versions, so TLS 1.2 and 1.3 are both accepted. (source: src/protocol/tls.rs, TlsConfig, build_server_config)

3. Startup and authentication

3.1 StartupMessage

handle_session parses the NUL-separated key/value pairs after the 8-byte header. user and database set SessionContext.user and SessionContext.database; every pair is also stored in SessionContext.variables. If the client sends no database, the session database stays at the SessionContext::new default, default. Other startup parameters (application_name, options, search_path, client_encoding) are stored but not applied to the engine. (source: src/protocol/postgres/mod.rs, handle_session; src/protocol/mod.rs, SessionContext::new)

3.2 Authentication methods

There is no trust method on this wire; every login presents a password. Which exchange runs depends on whether the role has a stored SCRAM verifier. (source: src/protocol/postgres/mod.rs, handle_session, scram_exchange, scram_enabled)

Method When Message sequence
SCRAM-SHA-256 SYNERGYDB_PG_SCRAM is not 0/false/off/no (default on), and the role exists, can log in, has a password, and has a verifier under __auth__:scram:<user> that matches its current Argon2id hash. Also used, with a mock verifier, for an unknown user or a role that cannot log in. Server R code 10 (AuthenticationSASL, mechanism list SCRAM-SHA-256); client p SASLInitialResponse; server R code 11 (SASLContinue, server-first-message); client p SASLResponse (client-final-message); server R code 12 (SASLFinal, v=<ServerSignature>); server R code 0.
Cleartext password SCRAM disabled, or the role has no valid verifier yet (first login after the password was set or changed). Server R code 3 (AuthenticationCleartextPassword); client p PasswordMessage; server R code 0.

Details of the SCRAM exchange (source: src/auth/scram.rs, ServerExchange::start, ServerExchange::finish, Verifier, mock_verifier):

  • The gs2 header must be n or y. A p= (channel binding requested) is a protocol error, so SCRAM-SHA-256-PLUS is never offered and libpq channel_binding=require is refused.
  • The user name comes from the StartupMessage; the n= attribute is ignored, as in PostgreSQL.
  • The server nonce is 18 random bytes, base64. Iteration count is DEFAULT_ITERATIONS = 4096.
  • The proof is checked with a constant-time compare of SHA256(ClientKey) against the stored key. A wrong proof is BadProof (wrong password); any parse failure, channel-binding mismatch or nonce mismatch is a protocol error.
  • SASL messages are capped at 16 KiB. (source: src/protocol/postgres/mod.rs, read_sasl_message)
  • An unknown user or a non-login role gets mock_verifier, a verifier with a per-name stable salt, so the exchange looks the same on the wire and fails at the proof.

Cleartext path: the password is checked against the role's Argon2id hash with verify_cache::verify_password_cached, which runs the KDF off the async workers, bounds concurrent KDFs and caches outcomes briefly. A missing user, a non-login role and a role with no password each spend one verify against a constant dummy hash so they are not distinguishable by timing. On success with SCRAM enabled, store_scram_verifier derives a SCRAM verifier from the cleartext and stores it tagged with the current Argon2id hash. In cluster mode only the leader stores verifiers. (source: src/protocol/postgres/mod.rs, handle_session, store_scram_verifier; src/auth/scram.rs, encode_record, decode_record)

A verifier is ignored when its tag no longer matches the role's Argon2id hash, so a password changed by any route retires it and the next login falls back to the cleartext exchange once. (source: src/auth/scram.rs, module comment, decode_record)

After every check the result goes to wire_auth::note_auth_result. After 5 consecutive failures for one user name, each further failure is delayed 200 ms, doubling to a cap of 5 s; the count resets after 10 minutes without a failure or on a success. It is keyed by user name, not address. (source: src/auth/wire_auth.rs, note_auth_result, auth_failure_delay)

Tested by: unit tests in src/auth/scram.rs (rfc7677_vector, full_exchange_and_record) and the live runs recorded in docs/status/2026-11-30-pg-scram.md (psql 16, asyncpg, node-pg; TLS on and off).

3.3 Failure replies

Case Reply
Wrong password, unknown user, non-login role ErrorResponse S=FATAL, C=28P01, M=password authentication failed for user "<name>", then close
Database dropped or never created ErrorResponse S=FATAL, C=3D000, M=database "<name>" does not exist, then close. Checked after authentication so an unauthenticated client cannot probe database names.
Plaintext refused under require_tls S=FATAL, C=28000 (section 2)

(source: src/protocol/postgres/mod.rs, handle_session)

3.4 After authentication

On success the server sends, in order (source: src/protocol/postgres/mod.rs, handle_session, default_server_params):

  1. AuthenticationOk (R, code 0).
  2. One ParameterStatus (S) per entry below.
  3. BackendKeyData (K): the process id is notifications::allocate_pid() (stable for the connection, also used in NotificationResponse), the secret is random.
  4. ReadyForQuery (Z, I).
Parameter Value
server_version 15.0
server_encoding UTF8
client_encoding UTF8
DateStyle ISO, MDY
integer_datetimes on
standard_conforming_strings on
IntervalStyle postgres
TimeZone Etc/UTC
is_superuser on
session_authorization postgres
default_transaction_read_only on on a cluster read-only replica, else off (read at each connect)
in_hot_standby same as above
application_name empty

search_path is not reported at startup. is_superuser and session_authorization are constants and do not reflect the logged-in role. ParameterStatus is sent only at startup; a later SET does not produce one. No NoticeResponse is ever sent. (source: src/protocol/postgres/mod.rs, default_server_params; grep finds no other caller of send_parameter_status_generic)

The session's QueryEngine is then bound to the database (set_database, the per-database namespace for all storage keys) and given an AuthenticatedSession resolved from the catalog (roles, RLS, column grants), plus the audit logger if configured. (source: src/protocol/postgres/mod.rs, handle_session)

4. Message loop

The loop reads a 5-byte header (type byte plus self-inclusive length) while racing the session's notification channel, so a NOTIFY from another connection is written to an idle client at once. A declared length under 4 closes the connection. A body over BufferLimits::max_message_size (default 256 MiB) gets an ErrorResponse with SQLSTATE 54000 and the connection closes. (source: src/protocol/postgres/mod.rs, handle_session, send_buffer_limit_error)

Frontend messages handled (the match msg_type in handle_session):

Byte Message Handling
Q Query Simple query (section 5). A query longer than max_query_length (default 16 MiB) gets SQLSTATE 54001 and the loop continues.
P Parse ExtendedQueryHandler::handle_parse
B Bind handle_bind
D Describe handle_describe (statement S or portal P)
E Execute LISTEN/UNLISTEN/NOTIFY/pg_notify/pg_listening_channels portals are handled in the loop; everything else goes to handle_execute
C Close handle_close (statement or portal), replies CloseComplete
S Sync Flush pending notifications, clear the batch error flag, send ReadyForQuery with the current status byte
H Flush handle_flush, a no-op; output is flushed by the loop when the next read would wait
X Terminate End the loop (cleanup runs)
any other   Logged as Unknown message type and ignored

FunctionCall (F) has no arm and is ignored. CopyData, CopyDone and CopyFail are read only inside a COPY FROM (section 7).

Extended-protocol error state. After a Parse, Bind, Describe, Execute or Close fails, the loop sets ext_err and skips every further P, B, D, E and C until Sync, as PostgreSQL does. Sync clears the flag. An Execute error inside a transaction moves the session to Failed, so the next ReadyForQuery carries E. (source: src/protocol/postgres/mod.rs, handle_session)

5. Simple query

handle_query_generic processes a Q message in this order (source: src/protocol/postgres/mod.rs, handle_query_generic):

  1. Aborted transaction. In Failed state only ROLLBACK, END, ABORT, COMMIT and RELEASE are accepted (leading SQL comments are skipped); anything else gets SQLSTATE 25P02 "current transaction is aborted, commands ignored until end of transaction block". COMMIT or END in a failed transaction is executed as ROLLBACK.
  2. Recovery read gate (cluster only). A read statement (statement_is_read: first keyword SELECT, WITH, TABLE, VALUES, SHOW, FETCH or EXPLAIN) on a node that has not caught up gets SQLSTATE 25006.
  3. Notifications. LISTEN, UNLISTEN, NOTIFY, SELECT pg_notify(...) and pg_listening_channels() are answered without the engine (section 8).
  4. Statement split. split_simple_query_statements splits on top-level ;, respecting single quotes, double quotes, dollar quotes and --//* */ comments. No statements left: EmptyQueryResponse (I) then ReadyForQuery. More than one: each runs through run_simple_statement; the first error sends one ErrorResponse and ReadyForQuery and stops the batch; otherwise a single ReadyForQuery ends the batch.
  5. COPY. A statement starting with COPY goes to handle_copy_command (section 7).
  6. System catalog. Unless the first word is CREATE, DROP, ALTER, INSERT, UPDATE, DELETE, TRUNCATE, GRANT, REVOKE, PREPARE, EXECUTE or DEALLOCATE, a query that SystemCatalog::is_catalog_query recognises (mentions pg_catalog, information_schema, pg_class, pg_attribute, pg_type, pg_namespace, pg_index, pg_constraint, pg_proc, pg_settings, pg_stat_*, current_database, current_schema, version(), pg_get_*, format_type, ::regclass, ::regtype, obj_description, col_description, the relation-size functions, among others) is answered by SystemCatalog::execute if it returns a result. (source: src/protocol/postgres/catalog.rs, SystemCatalog::is_catalog_query)
  7. Engine. Otherwise QueryEngine::execute(query, &[]) on the session engine.

Results are written as RowDescription (T), DataRow (D) batched into 256 KiB writes, CommandComplete (C), any pending notifications, then ReadyForQuery (Z). Simple-query results are always text format. In RowDescription the table OID and attribute number are 0 and the type modifier is -1. (source: src/protocol/postgres/mod.rs, handle_query_generic)

Command tags. QueryResult variants map to INSERT 0 n, UPDATE n, DELETE n, SELECT n, BEGIN, COMMIT, ROLLBACK, SAVEPOINT, RELEASE. DDL and utility tags come from the statement text through statement_command_tag: TRUNCATE TABLE, LOCK TABLE, DEALLOCATE/DEALLOCATE ALL, the bare verb for SET, RESET, SHOW, PREPARE, ANALYZE, VACUUM, REINDEX, EXPLAIN, COMMENT, GRANT, REVOKE, DO, CALL, CLUSTER, CHECKPOINT, DISCARD, LISTEN, UNLISTEN, NOTIFY, and CREATE|DROP|ALTER <object> for TABLE, INDEX, VIEW, MATERIALIZED VIEW, DATABASE, SCHEMA, SEQUENCE, FUNCTION, TRIGGER, EXTENSION, TYPE, ROLE, USER. A DML with RETURNING (which comes back as a Select) is tagged by its verb through select_path_command_tag. A CTE-wrapped DML (WITH ... INSERT) is still tagged SELECT n. (source: src/protocol/postgres/mod.rs, statement_command_tag, select_path_command_tag)

6. Extended query protocol

ExtendedQueryHandler keeps two maps per connection: statements (name to PreparedStatement) and portals (name to Portal). The empty name is the unnamed statement or portal. It does not own an engine; Parse, Describe and Execute use the session's single engine, so a BEGIN sent by simple query and an INSERT sent by extended query share one transaction. (source: src/protocol/postgres/extended.rs, ExtendedQueryHandler, PreparedStatement, Portal)

Parse (P)

Reads statement name, query text, parameter count (a negative count is an error) and parameter type OIDs. Then (source: src/protocol/postgres/extended.rs, handle_parse):

  • A LISTEN/UNLISTEN/NOTIFY/pg_notify/pg_listening_channels statement is stored with is_notification = true and not described.
  • Parameter type inference. If no types are given or all are 0, the types come from QueryEngine::detect_parameter_types. If some are 0 or 705 (unknown), those positions are filled from the detected list, and extra detected types are appended.
  • A text with more than one statement (Liquibase splitStatements=false blocks) is accepted, described as NoData, and run statement by statement at Execute. PostgreSQL rejects this; SynergyDB is more permissive.
  • asyncpg's WITH RECURSIVE typeinfo_tree query and Prisma's pg_class ... AS table_name ... AS namespace introspection are answered by SystemCatalog at Parse time and the rows are kept (catalog_rows) so Describe and Execute agree.
  • Everything else is described with QueryEngine::describe_query.

Reply: ParseComplete (1).

Bind (B)

Reads portal name, statement name, parameter format codes, parameter values (length -1 is NULL), and result format codes. Negative counts or lengths are rejected. Parameter formats are normalised to one code per parameter: no codes means all text, one code applies to all. Reply: BindComplete (2). Binding to an unknown statement is an error. (source: src/protocol/postgres/extended.rs, handle_bind; tests bind_rejects_negative_format_count, bind_rejects_negative_parameter_length, bind_rejects_negative_result_format_count)

Describe (D)

  • S (statement): ParameterDescription (t) with the stored or inferred OIDs, then RowDescription with format 0 for every column, or NoData (n) when there are no columns.
  • P (portal): first prefetch_portal_for_describe runs a read-only portal and keeps the result, so the RowDescription has the same column count as the DataRows Execute will send (statically derived descriptions missed shapes such as alias.* over a UNION). Then RowDescription with the portal's result formats, or NoData. A name that is not a portal but is a DECLAREd cursor is described from the cursor's columns. Prefetching is off when the cluster read gate is installed.

(source: src/protocol/postgres/extended.rs, handle_describe, prefetch_portal_for_describe; test test_describe_portal_matches_rows_for_alias_star_over_union)

Execute (E)

Reads portal name and max rows (0 = all). (source: src/protocol/postgres/extended.rs, handle_execute)

  • Cursor as portal. If there is no bound portal by that name but a DECLAREd cursor exists, rows are taken from the cursor (QueryEngine::cursor_take); when more remain the reply is PortalSuspended (s), else CommandComplete FETCH n. This is the path psycopg 3 server-side cursors use.
  • Cluster read gate: SQLSTATE 25006 for reads while catching up.
  • Otherwise the result comes from the Describe prefetch, the Parse-time catalog rows, the multi-statement path, or engine.set_params(...) followed by engine.execute(query, params). set_params passes the client's parameter OIDs and per-parameter formats so binary parameters are decoded by type.
  • DataRows are encoded with the OIDs that were described, not those the executor returned, whenever the column counts match. This keeps binary widths consistent with what the client was told.
  • Not verified / differs from PostgreSQL: for a normal portal with max_rows > 0, the first max_rows rows are sent and then CommandComplete; the remaining rows are dropped and no PortalSuspended is sent. Only cursor-backed portals suspend. No test was found for row-limited Execute on a normal portal.

Close (C), Sync (S), Flush (H)

Close removes the named statement or portal (and any prefetched result) and replies CloseComplete (3); an unknown name is not an error. Sync is handled in the loop (section 4). Flush is a no-op in the handler. (source: src/protocol/postgres/extended.rs, handle_close, handle_flush)

SQL-level PREPARE, EXECUTE and DEALLOCATE are separate from protocol-level statements; they run in the engine. (source: src/protocol/postgres/mod.rs, handle_query_generic, the is_user_dml_or_ddl list)

7. COPY sub-protocol

CopyHandler::is_copy_command matches any statement starting with COPY . CopyCommand::parse accepts (source: src/protocol/postgres/copy.rs, CopyCommand::parse, parse_format_opts):

  • COPY table [(col, ...)] TO|FROM <target> [WITH ...], with quoted and schema-qualified names.
  • COPY (SELECT ...) TO STDOUT [WITH ...]. A subquery with FROM is rejected: "COPY (SELECT …) only supports TO STDOUT".
  • Options, found by substring in the statement: FORMAT CSV / WITH CSV, FORMAT BINARY, DELIMITER 'c', NULL 'x' (also NULL AS 'x'), HEADER, QUOTE 'c', ESCAPE 'c', FORCE_NULL (cols|*), FORCE_NOT_NULL (cols|*). CSV sets the delimiter to , and the NULL string to the empty string; text defaults are tab and \N.

The text after TO/FROM is not checked: data always flows over the connection as if it were STDOUT/STDIN. There is no server-side file or PROGRAM access.

COPY TO (handle_copy_to): runs SELECT (the subquery, or the table with its column list), sends CopyOutResponse (H, overall format 0 or 1, per-column format codes), an optional CSV header line, one CopyData (d) per row, then CopyDone (c). The session then sends CommandComplete COPY n and ReadyForQuery. All rows are materialised before the first CopyData.

COPY FROM (handle_copy_from, handle_copy_from_inner):

  1. Checks whether the table is empty, then BEGIN on a fresh engine and begin_bulk_load (a never-written table may commit by bulk ingestion instead of the WAL).
  2. Gets the column list with describe_query("SELECT * FROM t WHERE 1=0"), sends CopyInResponse (G).
  3. Reads d (CopyData), c (CopyDone) or f (CopyFail). Any other message type is an error. CopyData is split into lines at \n; a UTF-8 sequence split across two CopyData messages is carried over. Empty lines are skipped, the CSV header line is skipped when HEADER is set, and an unquoted \. line ends the data in text and CSV formats.
  4. Rows are inserted in multi-row INSERT batches of COPY_BATCH_ROWS = 5,000.
  5. Every SYNERGYDB_COPY_COMMIT_ROWS rows (default 250,000; 0 = one transaction) the transaction commits and a new one starts, so memory is bounded by the chunk.
  6. On success COMMIT and COPY n. On failure ROLLBACK; if chunks were already committed and the table was empty at the start, it is truncated; if it was not empty, the committed rows stay and the error message says how many.

COPY runs in its own transaction, not the session's: a COPY inside a client BEGIN is not tied to that transaction. COPY uses the session's AuthenticatedSession for non-superusers, so table privileges and RLS apply. Rows from committed chunks are visible to other sessions while a large COPY is still running. (source: src/protocol/postgres/copy.rs, handle_copy_from doc comment; src/protocol/postgres/mod.rs, handle_copy_command; docs/status/2026-11-30-copy-bounded-memory.md)

Not wired: binary COPY data. FORMAT BINARY is parsed, but parsing a binary row returns Unsupported("Binary COPY format not supported"), and format_row emits text for binary output. (source: src/protocol/postgres/copy.rs, parse_row, format_row)

Tested by: tests/copy_wire_atomic.rs (real CopyData/CopyDone frames over a duplex stream: copy_batch_with_duplicate_key_leaves_nothing_behind, copy_end_of_data_marker_is_not_a_row_in_text_or_csv, large_copy_commits_in_chunks_and_a_failed_load_into_an_empty_table_leaves_nothing), tests/copy_bulk_parity.rs, and 27 unit tests in copy.rs for parsing and CSV/text field handling.

8. LISTEN / NOTIFY

NotificationRegistry is shared by every connection of the handler: a parking_lot::RwLock<HashMap> from channel name to a list of (pid, sender) slots. Each connection has an unbounded mpsc channel; LISTEN registers its sender. NOTIFY encodes one NotificationResponse frame (A, Int32 pid of the notifier, channel, payload) and sends it to every listener on the channel, culling closed senders. The frame reaches the client between the current response and ReadyForQuery, or at once if the connection is idle. (source: src/protocol/postgres/notifications.rs, NotificationRegistry::notify, encode_notification; src/protocol/postgres/mod.rs, handle_session)

Accepted forms: LISTEN ch, UNLISTEN ch, UNLISTEN *, NOTIFY ch[, 'payload'], SELECT pg_notify('ch', 'payload'), SELECT pg_listening_channels(). Channel names longer than 63 bytes and payloads longer than 8,000 bytes are not recognised as notification commands. These are handled in both the simple and the extended protocol. (source: src/protocol/postgres/notifications.rs, parse_listen_command, parse_notify_command, parse_pg_notify_call, MAX_CHANNEL_NAME_LENGTH, MAX_PAYLOAD_LENGTH)

Differences from PostgreSQL, from the code: a NOTIFY is delivered immediately, not at commit, and is not discarded by a rollback. Notifications do not cross cluster nodes (the registry is in process). Tested by 7 unit tests in notifications.rs; no end-to-end wire test was found.

9. How queries reach the engine

The PostgreSQL wire is SynergyDB's native SQL dialect: statements go to QueryEngine::execute without translation, apart from the catalog interception in section 5 step 6. The engine handles SET/SHOW, PREPARE/EXECUTE, cursors, savepoints, advisory locks, temp tables and the PostgreSQL function library; those are documented with the query engine. SHOW and current_setting defaults that are not set in the session come from QueryEngine::guc_default:

GUC Default
server_version / server_version_num 15.0 / 150000
server_encoding, client_encoding UTF8
datestyle ISO, MDY
timezone UTC
integer_datetimes, standard_conforming_strings on
transaction_isolation read committed
max_identifier_length 63
bytea_output hex
search_path "$user", public
transaction_read_only, default_transaction_read_only, in_hot_standby on on a read-only replica, else off

version() returns PostgreSQL 15.0 (SynergyDB 0.1.0, compatible). (source: src/query/engine.rs, guc_default; src/protocol/postgres/catalog.rs, the version() handler)

The server reports version 15.0, while the differential suites compare against PostgreSQL 16 (see the operator page).

10. Type mapping

Result columns carry a type OID chosen by the engine (ColumnInfo.type_oid, from PgTypeOid in src/query/types.rs and type_name_to_oid in src/protocol/postgres/catalog.rs). Values are held as text inside the engine and converted at the wire.

OID Type Declared names mapped to it Text output Binary output (format 1)
16 bool boolean, bool t / f (from true/t/1 and false/f/0) 1 byte
17 bytea bytea, blob, binary, varbinary \x hex raw bytes decoded from hex
18 / 1042 char / bpchar char, character, bpchar as stored UTF-8 bytes
20 int8 bigint, int8, bigserial as stored 8-byte big-endian
21 int2 smallint, int2 as stored 2-byte big-endian
23 int4 integer, int, int4, serial as stored 4-byte big-endian
25 text text, string, citext, hstore (catalog), ltree, lquery, cube, seg, and any unknown name as stored UTF-8 bytes
26 oid oid as stored 4-byte unsigned
114 json json as stored UTF-8 text
3802 jsonb jsonb as stored version byte 1 then UTF-8
700 float4 real, float4 as stored 4-byte IEEE
701 float8 double precision, float8, double, float as stored 8-byte IEEE
1700 numeric numeric, decimal as stored PostgreSQL base-10000 numeric (ndigits, weight, sign, dscale, digits); NaN form if the text does not parse
1043 varchar varchar, character varying as stored UTF-8 bytes
1082 date date as stored int32 days since 2000-01-01
1083 / 1266 time / timetz time, timetz as stored UTF-8 text
1114 timestamp timestamp, datetime YYYY-MM-DD HH:MM:SS[.ffffff], no zone int64 microseconds since 2000-01-01
1184 timestamptz timestamptz, timestamp with time zone same with +00 int64 microseconds since 2000-01-01 UTC
1186 interval interval as stored int64 microseconds, int32 days, int32 months
2950 uuid uuid as stored 16 bytes
3614 / 3615 tsvector / tsquery same as stored UTF-8 text
16384 vector (pgvector) vector, vector(n) as stored int16 dim, int16 unused, float4 per element
16390 hstore hstore in result columns as stored UTF-8 text
1000, 1005, 1007, 1009, 1015, 1016, 1021, 1022, 1231, 2951 arrays of bool, int2, int4, text, varchar, int8, float4, float8, numeric, uuid <elem>[] PostgreSQL array text {...} array header plus each element in its own binary form
869, 650, 829, 790, 1560, 1562, 142, 600-604, 628, 718 inet, cidr, macaddr, money, bit, varbit, xml, geometric types the type names as stored UTF-8 text

Timestamp text is normalised at the wire by ts_to_pg_wire: the engine's internal ISO form (2026-07-11T14:55:54.273706Z) becomes 2026-07-11 14:55:54.273706 for OID 1114 and ... +00 for OID 1184. A zone left on a timestamp value is dropped. (source: src/protocol/postgres/mod.rs, ts_to_pg_wire; tests timestamp_zone_matches_the_declared_type, timestamp_fraction_and_utc_offset_match_postgres)

Binary encoding of any OID not listed with a binary form falls back to the text bytes. A binary integer or float that does not parse also falls back. (source: src/protocol/postgres/extended.rs, value_to_binary, array_to_binary, encode_numeric_binary; tests numeric_100_00, numeric_negative_fraction, numeric_pure_fraction, numeric_large_integer, numeric_zero_keeps_scale, numeric_nan_and_bad_input, binary_timestamp_out_of_range_returns_none, binary_date_out_of_range_returns_none, interval_text_round_trips)

Result column OIDs are checked against PostgreSQL 16 by the differential harness (test-scripts/diff/diff_harness.py, which flags WRONG_TYPE unless --no-types).

11. Error mapping

Errors are sent as ErrorResponse with only the fields S (severity ERROR), C (SQLSTATE) and M (message); a code comment records that adding V, F or R fields hung psycopg2. Internal schema\x1fname relation names are shown as schema.name. A constraint error's message has no Constraint violation: prefix. After the error, ReadyForQuery is sent with E if the session was in a transaction (which moves it to Failed), else I. (source: src/protocol/postgres/mod.rs, send_error_with_state, pg_error_message)

PostgresHandler::error_to_sqlstate maps engine errors (source: src/protocol/postgres/mod.rs, error_to_sqlstate; test duplicate_key_is_23505_with_pg_message):

Engine error SQLSTATE
TableNotFound 42P01
ColumnNotFound 42703
IndexNotFound 42704
Schema "… already exists" for relation, table or index 42P07
Schema "… already exists" for function or procedure 42723
Schema "… already exists", other objects 42710
Schema, other 42000
Constraint mentioning unique or duplicate 23505
Constraint mentioning not null or null value 23502
Constraint mentioning foreign key 23503
Constraint mentioning check 23514
Constraint, other 23000
Parse 42601
AmbiguousColumn 42702
GroupingError 42803
Semantic 42000
QueryExecution "schema … already exists" 42P06
QueryExecution "schema … does not exist", "no schema has been selected to create in" 3F000
QueryExecution "cannot drop schema …" 2BP01
QueryExecution "unacceptable schema name …" 42939
QueryExecution "… is not yet defined in this session" (currval before nextval) 55000
QueryExecution "prepared statement … does not exist" 26000
QueryExecution, other XX000
QueryTimeout 57014
DivisionByZero 22012
NumericValueOutOfRange 22003
StringDataRightTruncation 22001
CardinalityViolation 21000
Unsupported 0A000
PermissionDenied 42501
InvalidInput from pgvector checks 22000
InvalidArgument "cannot take square root of a negative number" 2201F
InvalidArgument, InvalidInput 22023
TypeMismatch 22P02
TransactionConflict 40001
TransactionAborted 25P02
Deadlock 40P01
LockTimeout, LockNotAvailable 55P03
SavepointNotFound 3B001
ReadOnly (write on a Raft follower) 25006
Io, Wal, SSTable, Compaction, Corruption 58000
anything else XX000

Errors raised by the wire layer itself:

Situation SQLSTATE
Message over max_message_size 54000
Query over max_query_length 54001
Too many columns / parameters (buffer limit errors) 54011 / 54023
Aborted transaction 25P02
Cluster node catching up 25006
send_error_generic without a code (e.g. "Extended query protocol requires storage engine") 42000
COPY without a storage engine 08006
Authentication 28P01, 28000, 3D000 (section 3.3)

(source: src/protocol/postgres/mod.rs, send_buffer_limit_error, send_error_generic, handle_copy_command; src/protocol/buffer_limits.rs, pg_error_codes)

The differential phase scripts compare errors by SQLSTATE (test-scripts/diff/phases_pg.py).

12. Limits and configuration

Setting Default Where set
server.postgres_port 5432 (validation refuses 0) config file / SYNERGYDB_SERVER_POSTGRES_PORT
[tls] enabled, cert_path, key_path, require_client_cert, ca_cert_path, require_tls see the configuration reference config file
SYNERGYDB_PG_SCRAM on env
SYNERGYDB_PG_THREAD_PER_CONN on env
SYNERGYDB_INLINE_EXEC reads env
SYNERGYDB_INLINE_LIMIT 32 env
SYNERGYDB_COPY_COMMIT_ROWS 250000 env
SYNERGY_PG_TRACE off env
Max message size 256 MiB BufferLimits::default
Max query length 16 MiB BufferLimits::default
Startup read timeout 60 s TimeoutConfig::default
SASL message size 16 KiB read_sasl_message
Password message at most 64 KiB (the read buffer) handle_session
COPY insert batch 5,000 rows COPY_BATCH_ROWS
NOTIFY channel / payload 63 / 8,000 bytes notifications.rs

BufferLimits and TimeoutConfig have builder methods (with_buffer_limits, with_timeout_config), but the server does not call them, so the defaults above are fixed in a running server. Only the startup read uses the read timeout; there is no idle timeout on an established session. (source: src/server/mod.rs; src/protocol/postgres/mod.rs, handle_connection; src/protocol/buffer_limits.rs; src/protocol/timeout.rs)

13. Code that is not wired

  • src/protocol/postgres/auth.rs defines PostgresAuthenticator with trust, cleartext, MD5 and SCRAM methods, and PostgresAuthConfig (method, trust_localhost, require_ssl_for_remote). Nothing outside that file uses PostgresAuthenticator; PostgresAuthConfig is stored on the handler but never read. The live authentication path is the one in section 3. MD5 and trust are therefore not available. (source: grep for PostgresAuthenticator and auth_config in src/)
  • LEGACY_AUTH_HASHES is an empty map kept for a fallback path; it is never populated. (source: src/protocol/postgres/mod.rs, get_legacy_auth_hashes)
  • ExtendedQueryHandler::handle_sync is unused; the loop uses handle_sync_status.

14. Tests and suites

Test or suite What it covers
tests/protocol_postgres.rs (65 tests) Mostly SQL through QueryEngine (DDL, DML, types, predicates, aggregates, joins, subqueries, transactions, error cases) plus PostgresHandler construction. It does not open a socket or exercise wire framing.
tests/copy_wire_atomic.rs COPY FROM over the real handler with real frames: atomicity, \. marker, chunked commits
tests/copy_bulk_parity.rs COPY's bulk row path (QueryEngine::copy_insert_rows) writes the same keys and row bytes and raises the same constraint errors as the INSERT path, and declines table shapes it does not model
tests/pg_class_reltuples.rs pg_class.reltuples catalog answer
Unit tests in src/protocol/postgres/ mod.rs 5 (read classification, timestamp text, 23505 mapping), extended.rs 14 (numeric/interval/timestamp binary, Bind validation, Describe/rows agreement, parameter inference), copy.rs 27, notifications.rs 7, catalog.rs 27, catalog/pg_dump.rs 4, auth.rs 7 (for the unwired authenticator)
src/auth/scram.rs unit tests RFC 7677 test vector, full exchange, stored-record handling
test-scripts/diff/diff_harness.py with corpus.py, schema.py Same schema, seed and read-query corpus on SynergyDB and PostgreSQL 16 through psycopg; compares typed values and result column OIDs
test-scripts/diff/phases_pg.py Phase 2 (second connection: visibility, isolation levels, unique waits, row locks, write skew, DDL visibility, sequences, temp tables, per-connection prepared statements and settings) and phase 3 (kill, restart, re-read)
test-scripts/feature-matrix/ (features.py, feature_matrix.py) One self-contained scenario per PostgreSQL feature, run on both engines with rollback after each; verdicts PARITY / DIVERGE / UNSUPPORTED / PG-ONLY / SETUP-FAIL
Proof logs docs/proof/2026-11-30/proof-pack-a3232c9/logs/postgres-query-corpus.txt, postgres-second-connection-restart.txt, postgres-feature-matrix.txt

The scores from these runs are on the operator page. tests/wire_preauth_gate.rs does not include the PostgreSQL wire; no test was found that sends a Query before authentication completes on this wire.