Registry Mirror
Skip to content

Conversation

@MisterRaindrop

@MisterRaindrop MisterRaindrop commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Stack, part 6 of 7 (draft). Depends on #2474. This PR also carries the
commits of #2470..#2474; its own change is the last commit, "datalake_fdw:
add merge-on-read UPDATE and DELETE". Part after it: #2476.

Closes #2020. Part of #2008.

What does this PR do?

UPDATE and DELETE of Builtin catalog tables, the Iceberg v2
merge-on-read way: a changed row is not rewritten in its data file;
its position is recorded in a position delete file, which every Iceberg
reader applies when it reads the data file.

  • Recording positions. The scan encodes each row's file (an index into
    the plan's file list) and its ordinal in that file into the row's ctid.
    The segment a changed row is routed to records that position. At the end of
    the statement it writes the positions as a sorted position delete file
    with the columns Iceberg requires. An UPDATE also writes the new row
    through the same writer as an INSERT.
  • Planning. UPDATE target lists are expanded in the planner, so the
    full new row is at hand without fetching the old one by ctid.
  • Reading. The scan applies each position delete file to the data files
    the agent assigned it to, and skips the deleted rows.
  • Committing. The transaction's deletes are staged as one Iceberg
    Update that the agent checks against everything committed since the
    snapshot the statement read.

Decisions worth a look:

  • An UPDATE or DELETE locks the table's HEAD before it reads, until
    its transaction ends
    , so no other writer commits under it.
    • Under READ COMMITTED, it waits out a writer that holds the lock and
      then changes the version that writer committed.
    • Under REPEATABLE READ and SERIALIZABLE, the version it locks must be
      the one the transaction's snapshot sees. If another transaction committed
      a newer one -- before the lock or while waiting for it -- the statement
      fails with SQLSTATE 40001, as an UPDATE of a heap row changed since the
      snapshot does. Without this rule, such a transaction could delete a row
      it never saw.
    • The cost: the conflict is judged per table, not per row, so it fails in
      cases where a heap table would not. Rejected: failing under
      READ COMMITTED too, which would fail concurrent writers more often
      than heap tables do.
    • INSERT-only transactions are unaffected at every level: their files go
      on whatever version is current when they commit.
  • A row matched twice is changed once. Deleted positions are kept as a
    bitmap per data file, one entry per 256 positions; the second hit on a
    position reports the row as already changed (TM_SelfModified), as a heap
    table does for a join that matches a row twice.
    • Measured on one segment deleting 1.33 million rows: 0.59 MB for the
      bitmaps, against 80.1 MB for a hash entry per deleted row, with
      identical delete files.
    • The cost: one row in every 256 positions, spread over a large file, takes
      about a hash entry per row, a little more than the hash would. The
      positions are still held in memory until the statement ends; nothing
      spills to disk.
  • Refused before anything is written: MERGE, DELETE ... RETURNING,
    UPDATE or DELETE of a table with row triggers, and reading equality
    delete files, which other engines may write.
  • Known limits, in the README: the agent's conflict check is not narrowed
    to the rows a statement read; a position delete file applies to every
    older data file, so reading costs more as deletes accumulate until a
    compaction exists.

Type of Change

  • Bug fix (non-breaking change)
  • New feature (non-breaking change)
  • Breaking change (fix or feature with breaking changes)
  • Documentation update

Test Plan

  • Integration tests added/updated: builtin_agent_dml (updates,
    deletes, joins that match a row twice, savepoints, a version without a
    snapshot) and dml_concurrent.sh (8 two-session checks: concurrent
    writers, and the isolation rules above for REPEATABLE READ,
    READ COMMITTED and INSERT) against a real agent and S3.
  • Passed make installcheck of contrib/datalake_fdw: 22 tests, 0
    failures; make installcheck-builtin-agent: 3 tests, the concurrent
    INSERT checks and the concurrent DML checks, 0 failures. Extension
    built with 0 warnings; mvn -B verify: 126 tests, 0 failures.

Impact

User-facing changes: Builtin catalog tables can be changed with UPDATE
and DELETE. Under REPEATABLE READ and SERIALIZABLE, a concurrent commit
to the same table makes an UPDATE or DELETE fail with a serialization
error, to be retried as with heap tables.

Checklist

Additional Context

Draft until the parts before it are merged. Next: #2476, hidden
partitioning.

Add contrib/datalake_agent, the Java gRPC service that datalake_fdw talks
to over the contract in contrib/datalake_agent/proto. This establishes the
process, transport, error and version handling, configuration, and logging
scaffolding before Iceberg operations and catalog providers fill in RPC
bodies.

Startup runs in this order: Main builds the Guice graph; the server
registers every service and binds the endpoint with
grpc.health.v1.Health answering NOT_SERVING, then becomes ready: it
starts the parent-process watchdog (--parent.pid) and flips health to
SERVING. Until then a business call is answered UNAVAILABLE "dlagent is
not ready", which a client may retry since the call did not run.
Handlers run on a bounded pool. Any startup failure exits 1. Default
transport is a Unix domain socket with configured file mode, guarded by
a lock on <socket>.lock that the agent holds for its lifetime, so a
second agent on the same path refuses to start rather than take the
socket over; TCP requires TLS and a mode-0600 bearer token file
supporting live rotation.

Every failure returns an ErrorDetail with BusinessErrorCode, retryable
flag, and correlation id; unexpected exceptions return a generic INTERNAL
without leaking stack traces. Every response carries contract version
headers, and incompatible clients are refused with FAILED_PRECONDITION.
All IcebergCatalogService RPCs (and opt-in CatalogManagementService RPCs)
currently answer UNIMPLEMENTED naming the RPC.

Settings come from the packaged application.properties, overridden by the
environment and by --key=value arguments, with relaxed binding and
placeholders as Spring Boot defines them; they hold process settings
only. The agent logs to dlagent-YYYY-MM-DD.log under --logging.file.path
(default $COORDINATOR_DATA_DIRECTORY/log; with neither it refuses to
start), with java.util.logging bridged in. RequestOptionMapper maps
datalake_fdw server and user mapping options to Iceberg catalog/FileIO
properties while keeping credentials in StorageConfig.credentials. A Log4j
rewrite policy scrubs request credentials and bearer tokens across agent,
Netty, and gRPC logs.

Add unit, in-process, UDS, TCP/TLS, process-level (cold start, logging,
watchdog), and credential-scrubbing tests under mvn -B verify along with
the datalake-agent CI workflow.

Closes apache#2011.
Replace the default stub metadata engine with the gRPC-backed agent engine
(src/meta/engine_agent) and add DL_ERR_CONFLICT (reported as serialization
failure) to distinguish optimistic concurrency conflicts from I/O or
internal errors.

Split the client cleanly across a plain C boundary: agent_engine.c runs in
PostgreSQL (settings, MetaCtx conversion, wait events, per-backend RPC
accounting for EXPLAIN ANALYZE), while agent_rpc.cpp drives gRPC
completion-queue polls with signal masking and query cancellation checks
without including server headers or letting C++ exceptions/longjmps cross.

Carry the table lifecycle family (CreateTable, LoadTable, DropTable,
TableExists) with an initial health/version handshake, ErrorDetail-based
error mapping, credentials routed via StorageConfig.credentials, and
build-time stub generation from contrib/datalake_agent/proto and
fragment.proto, with LLVM bitcode rules for the generated sources.
Builds without gRPC still succeed and report clear errors on agent
calls. Add datalake_fdw.meta_engine_for_testing for stub-only regression
clusters.

An agent that is still starting is waited for: a handshake answered
NOT_SERVING, and a call the agent's readiness gate refused with
UNAVAILABLE "dlagent is not ready", are tried again every 200 ms within
the RPC's one deadline, with the cancel check between tries. No other
UNAVAILABLE is replayed, since such a call may have run.

Add meta_conformance, fake_agent, and real-agent plumbing tests, and update
CI to build datalake_fdw with gRPC on Rocky 9/10 (and verify the no-gRPC
fallback on Rocky 8) and run agent tests against a live datalake_agent,
started with its socket and log directory as arguments.

Closes apache#2012.
Implement the catalog-free Iceberg kernel in datalake_agent where every
operation targets an explicit, immutable metadata_location (or table
location for CreateTable) supplied by the caller alongside volume storage
options and credentials.

Support CreateTable (exclusive initial metadata file, one create at a
time per table location), LoadTable, TableExists, GetStatistics,
DropTable (UUID check and optional purge), GetFragment (back-pressured
streaming splits with pooled delete files and residual filters),
PlanFileGroups (per-partition bin-packing), and staged Append/Update
writes returning a new metadata file as staging_id. Filters on nested
fields bind by full column path, and 64-bit counts travel as decimal
strings. Add idempotent operation_id handling with deterministic staged
paths, claim coalescing, and payload-mismatch rejection. Requests
without a location and catalog-level commits stay UNIMPLEMENTED.

Wire per-configuration leased S3FileIO and Hadoop-free LocalFileIO on
iceberg-java 1.12.0, speaking the settled 1.0.0 contract (optional
snapshots/sequence numbers, Iceberg JSON schemas/specs, file format and
content enums, column metrics, and credentials restricted to
StorageConfig.credentials).

Add local kernel, in-process gRPC, S3 end-to-end (SeaweedFS in CI), and
datalake_fdw agent_location lifecycle regression tests.

Closes apache#2013.
Implement the Builtin catalog layer on top of the metadata engine using an
extension table (iceberg_builtin_head) maintained exclusively on the
coordinator to store each Builtin table's current metadata_location and
UUID.

Moving a table's HEAD pointer updates its row under a row lock so pointer
transitions commit and roll back transactionally and concurrent writers
serialize cleanly via builtin_catalog_swap(). CREATE TABLE creates the
initial metadata file under <base_path>/<schema>/<table>_<relid> and
records its pointer; DROP TABLE removes the pointer and defers purge
until post-commit so rolled-back drops preserve table data. Expose
iceberg_builtin_heads() to inspect current versions.

CREATE TABLE sends the table's Iceberg schema, built from its columns
(pg_iceberg_schema.c).  A Builtin table on a file:// volume is refused,
since nothing there creates its directories or makes its files durable.
Each HEAD row records the database that created it: a database copied
with CREATE DATABASE ... TEMPLATE refuses to use the copied tables, and
dropping one there leaves the files to the database they belong to.  The
stub engine marks the locations it invents and answers only for those,
and the agent engine refuses a marked location.

Add stub and concurrency tests (iceberg_am_builtin, builtin_concurrent.sh),
S3 external-engine interoperability tests verifying Iceberg Java opens
staged Builtin metadata directly, and the installcheck-builtin-agent CI
run against a live agent.

Closes apache#2014.
Implement end-to-end INSERT and SELECT for Builtin catalog Iceberg tables
along with NUMERIC(p,s) / Iceberg decimal support:

- Write path: the access method hands each row to the modify routines
  (pg_iceberg_modify.c), which keep, for each table a statement writes on
  a segment, where its files go and the data writer the rows go to
  (pg_iceberg_data_writer.c, behind pg_iceberg_writer.h).  The writer
  puts Parquet data files under the table data directory, rolling at
  iceberg.target_file_size and bounding row groups by memory.  At
  ExecutorFinish each segment reports the files it wrote to the
  coordinator via libpq 'y' messages collected in
  ProcessDispatchResult_hook.
- Transaction-level commit: the coordinator hands each statement's files
  to the transaction's tracker (pg_iceberg_tracker.c), and at PRE_COMMIT
  commits everything the transaction wrote to a table as one Iceberg
  snapshot, by locking the Builtin pointer, staging an Append of all the
  files on the current version, and swapping HEAD.  A transaction that
  rolls back leaves no snapshot, and a savepoint that rolls back takes its
  statements' files with it.  A statement that reads a table the
  transaction wrote reads a version staged the same way and kept to the
  transaction.  PREPARE TRANSACTION of a transaction that wrote a lake
  table is refused, and DROP TABLE with purge_on_drop also removes the
  files the dropping transaction wrote.
- Read path: a planner hook replaces SeqScan on lake tables with an
  Iceberg CustomScan.  On each execution the coordinator plans the
  version the statement reads into a plan copy so kept plans see current
  data, distributing fragments across segments with Iceberg field-id
  projection.
- Credentials: data files are accessed with the table owner's volume
  user mapping.  An INSERT in a database copied from another is refused
  before any segment writes.
- NUMERIC/DECIMAL: map numeric(p,s) (p <= 38, 0 <= s <= p) to Iceberg
  decimal(p,s) and Arrow decimal128 with exact unscaled conversion, NaN
  rejection, precision widening on read, and overflow checks.
- Checks: the coordinator refuses a segment report that names a file
  twice or a table the statement does not write, and a fragment batch of
  another contract version.  TIME '24:00:00', valid in PostgreSQL but
  past the end of an Iceberg time, is refused on write and on read.

UPDATE, DELETE, MERGE, SELECT ... FOR UPDATE or FOR SHARE, INSERT into a
table with AFTER INSERT row triggers, and reading a table that has delete
files are refused before anything is written.  CREATE TABLE in a database
whose encoding is not UTF-8 is refused before anything is created.  COPY
stays refused, and its error points at pg_dump --inserts or
--column-inserts for backing lake tables up.

Add builtin_agent_rw, insert_concurrent.sh, and Parquet decimal round-trip
regression tests.

Closes apache#2018, apache#2019, apache#1988.
Change the rows of Builtin catalog tables the Iceberg v2 merge-on-read
way:

- Position deletes: the scan encodes each row's file index and row
  ordinal into its ctid, so the segment a changed row is routed to records
  the deleted position, deduplicated per row for joins via
  TM_SelfModified and kept as a bitmap per data file and 256 positions.
  At the end of the statement the position delete writer
  (pg_iceberg_delete_writer.c) writes them as a sorted Iceberg position
  delete file, with the required columns Iceberg declares; an UPDATE
  also writes the new row through the data writer.
- Planning and reading: UPDATE target lists are expanded in the planner so
  the full new row is available without a TID fetch.  The read path
  applies each position delete file to the data files the agent assigned
  it to and skips deleted rows, refuses equality deletes, and refuses a
  fragment that names one delete file twice.  MERGE, DELETE ...
  RETURNING, and UPDATE or DELETE of a table with row triggers are
  refused.
- Transactions: an UPDATE or DELETE locks the table's pointer as it lists
  the table, so the version it reads is the one its commit is staged on.
  The tracker notes the snapshot that version had, and stages a
  transaction that wrote delete files as an Update the agent checks
  against whatever was committed since, sending no starting_snapshot_id
  when the version read had no snapshot.  A savepoint that rolls back
  takes the noted snapshot with it.  Under REPEATABLE READ and
  SERIALIZABLE, an UPDATE or DELETE whose table has a version newer than
  the transaction's snapshot fails with a serialization error, as on a
  heap table; under READ COMMITTED it waits for the writer and reads the
  version that writer committed.

Add builtin_agent_dml, dml_concurrent.sh, and no-snapshot update tests.

Closes apache#2020.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

datalake_fdw: merge-on-read and DML

1 participant