Registry Mirror
Skip to content

Conversation

@MisterRaindrop

@MisterRaindrop MisterRaindrop commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

Stack, part 1 of 7. Depends on nothing beyond main. The parts after it
build on this one: #2471 → #2472 → #2473 → #2474 → #2475 → #2476.

Closes #2011. Part of #2008.

What does this PR do?

Adds contrib/datalake_agent, the Java gRPC service that datalake_fdw will
call for Iceberg metadata, with everything except the Iceberg operations:
process lifecycle, transport, authentication, errors, version checks,
configuration and logging. It implements the contract merged in #2071. Every
Iceberg RPC still answers UNIMPLEMENTED with its own name; #2472 fills them
in. The PostgreSQL build is unchanged: the agent is a separate Maven module.

Decisions worth a look:

  • Startup is sequential: compose, listen, then become ready. The server
    binds with every service registered and grpc.health.v1.Health answering
    NOT_SERVING; only then does it start the parent-process watchdog
    (--parent.pid) and flip health to SERVING. Until then a business call
    is answered UNAVAILABLE "dlagent is not ready", which a client may retry
    because the call never ran. Any startup failure exits with status 1.
  • A Unix socket by default; TCP only with TLS and a bearer token. The
    socket gets mode rw-rw---- once bound. TCP needs a certificate, a key and
    a token file of mode 0600, re-read when it changes so tokens rotate (two
    are accepted during a rotation). Rejected: plain TCP. The agent reads and
    writes storage with the credentials in each request and with its own
    ambient ones (local files, the AWS default chain), so an open port would
    lend both to anyone who can reach it.
  • The socket path has a lock file, <socket>.lock, held for the agent's
    lifetime.
    Netty deletes whatever is at the path before it binds, and
    deletes the path by name when it closes. Without the lock, a second agent
    started on the same path takes the socket over silently, and the first
    one's shutdown then deletes the second one's socket. With it, the second
    agent refuses to start without touching the socket. The lock file stays on
    disk after a stop; deleting it would reopen the race.
  • Every failure ends in one ErrorDetail (business code, retryable flag,
    correlation id) inside a google.rpc.Status. An unexpected exception
    reaches the client only as a generic INTERNAL with a correlation id; its
    stack trace stays in the log. Each failed call leaves one INFO line under
    the id the client was given.
  • Versions are checked on every call. A client sends
    x-cloudberry-client-version, every response carries the server's version
    and the oldest client it accepts, and a client too old is refused with
    FAILED_PRECONDITION.
  • Settings come from the packaged application.properties, overridden by
    the environment and by --key=value arguments, with Spring-style relaxed
    binding. They are process settings only; storage settings arrive with each
    request.
  • Logs go to a daily file under --logging.file.path (default
    $COORDINATOR_DATA_DIRECTORY/log; with neither the agent refuses to
    start), with java.util.logging bridged in. A Log4j rewrite policy scrubs
    credentials and bearer tokens from every line, Netty's and gRPC's
    included.
  • At most dlagent.grpc.handler-threads (200) calls run at once. The
    cost: beyond that, calls queue without a bound, health checks included, so
    when storage stalls the queue grows and health checks wait. A queued call
    whose deadline passes, or that its client cancels, ends for the client at
    once and is dropped without running. The README states this.
  • Java 17 is required, because Iceberg 1.12 (in datalake_agent: serve Iceberg tables by metadata location #2472) is built for it.
    The README covers a system JDK and one unpacked into $GPHOME/ext/jdk,
    which cloudberry-env.sh already puts on the PATH.

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

  • Unit tests added/updated: mvn -B verify, 87 tests, 0 failures, on
    Rocky Linux 9.8 (aarch64) with OpenJDK 17. They cover the interceptor
    chain in process, the Unix socket (including two agents on one path),
    TCP with TLS and token rotation, an unreadable token file, process
    start, logging and the watchdog, and credential scrubbing.
  • Apache RAT: 55 files approved, 0 unknown.
  • CI: .github/workflows/datalake-agent.yml (renamed from
    datalake-proto.yml) keeps the proto generator checks and adds
    mvn -B verify on Java 17.
  • Passed make installcheck (no C change)
  • Passed make -C src/test installcheck-cbdb-parallel (no C change)

Impact

User-facing changes: none until an extension uses the agent (#2471).

Dependencies: a new Maven module: gRPC 1.81.0, protobuf 3.25.5, Netty
4.1.132.Final, Guice 5.1.0, Log4j 2.24.3. Nothing new for the PostgreSQL
build.

Checklist

  • Followed contribution guide
  • Added/updated documentation (contrib/datalake_agent/README.md)
  • Reviewed code for security implications
  • This PR contains AI-assisted code generation
  • Requested review from cloudberry committers

Additional Context

Next in the stack: #2471, the client in datalake_fdw.

Comment on lines +123 to +141
/**
* The threads handlers run on, bounded.
*
* Without an executor grpc-java runs handlers on an unbounded cached pool,
* and every handler here blocks -- on a catalog, on object storage -- so a
* burst of calls would be a burst of threads. The queue is unbounded on
* purpose: a call beyond the thread count waits for a thread instead of
* failing, since the client does not retry a rejected call. Health calls
* share the pool, so a pool saturated by stalled calls delays a probe too.
*/
private static ThreadPoolExecutor handlerExecutor(int threads) {
AtomicInteger n = new AtomicInteger();
ThreadPoolExecutor executor = new ThreadPoolExecutor(threads, threads,
60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(),
r -> daemon("datalake-agent-grpc-" + n.incrementAndGet()).newThread(r));
// Idle threads go away, so the bound is a ceiling and not a cost.
executor.allowCoreThreadTimeOut(true);
return executor;
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we have some problems:

  • If agent drop then we lost queue with unprocessed requests.
  • If connect drop then we can not replay request automatically. It seems we can’t predict the outcome of the operation that has already begun. The client is seeing a network error, even though the data has already been recorded.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This cannot happen for a Builtin catalog table, because the agent does not commit it. The agent only writes a new metadata file; the coordinator moves the table's HEAD in its own transaction (#2473, #2474).

  • If the agent dies or the connection drops, the transaction fails and rolls back, so HEAD does not move. The new metadata file is left unused; the README lists this as a known limit.
  • The client does not retry calls. The only retry is for "dlagent is not ready", which the agent returns before it does any work (datalake_fdw: add the agent engine gRPC client #2471).

With an external catalog such as Polaris, the catalog does the commit, and a lost reply cannot be prevented. It can be made safe: each commit will carry an id stored in the snapshot, so after a lost reply the agent can check the table to see whether the commit landed, and a resent commit is recognised instead of applied twice. Iceberg's REST client already sends an Idempotency-Key when the catalog supports one. What cannot be made atomic is the catalog commit together with the PostgreSQL transaction; we will make the catalog commit the last step, so that nothing can fail after it. External catalogs are not in this series; this will be part of their design.

# client's limit in datalake_fdw.
dlagent.rpc_max_message_size=64
# The most calls served at once. A call beyond it waits for a thread.
dlagent.grpc.handler-threads=200

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is a large number because such usage can lead to frequent context switching on the CPU, even though we usually use significantly fewer cores.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

200 is an upper limit, not a fixed pool: threads start when calls arrive and stop after 60 seconds idle. A handler spends most of its time waiting on the catalog or object storage, and a waiting thread uses no CPU, so it adds no context switches. Only the coordinator calls the agent, so the number of active calls is about the number of running statements on lake tables. The limit can be changed with dlagent.grpc.handler-threads. If you have a measurement that points to a better default, I'm happy to change it.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Got it. I’m fine leaving it configurable as proposed.

}

private String resolve(String raw, int depth) {
if (depth > 8) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why 8? Is there an example of the maximum permissible string size?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

8 was not a string size. It was the maximum nesting of placeholders (${a} pointing to ${b}, and so on), only there to stop cycles like a=${b}, b=${a}. The number had no real reason, so I removed it. The code now detects cycles directly: any chain without a cycle resolves, and a cycle fails with a message that shows it, for example placeholder cycle: ${b} -> ${c} -> ${a} -> ${b}. Tests are in DlConfigTest. Fixed in 43376e6.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

8 was not a string size. It was the maximum nesting of placeholders

Yup, that’s what I meant)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good solution, I want suggest like that.

} catch (IOException ignored) {
// Stopping anyway; the next start removes a stale socket itself.
}
lock.release();

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we add release in finally block?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 43376e6. This is safe even when deleting the socket fails: the next agent takes the lock first and then removes the old socket.

try {
Files.deleteIfExists(config.udsPath());
} catch (IOException ignored) {
// Stopping anyway; the next start removes a stale socket itself.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we log a warning with the socket path?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 43376e6. The message is could not remove the socket <path>: <error>; the next start removes it.

While testing it, I found that this warning was lost on SIGTERM: Log4j's own shutdown hook runs at the same time as the agent's and stopped logging first. The agent now disables that hook (shutdownHook="disable") and stops Log4j itself after the agent has stopped. MainProcessTest.aSocketThatCannotBeRemovedAtStopIsLogged checks this; it fails without the Log4j change.

try {
channel.close();
} catch (IOException ignored) {
// The lock goes with the process anyway.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we log a warning with the lock-file path if channel.close() fails?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 43376e6. The message is could not close the socket lock file <path>: <error>; the lock goes with the process.

case STRUCT_VALUE -> value.getStructValue().getFieldsMap().values()
.forEach(v -> addScalars(v, into));
default -> {
// Numbers and booleans are not credentials anyone could recognise in a log.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why? I would wrote: Collect only string values, including those nested in lists and structs. I suggest delete the default block and change comment.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in 43376e6: removed the default block and used your comment.

Comment on lines +262 to +264
default -> {
// Numbers and booleans are not credentials anyone could recognise in a log.
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
default -> {
// Numbers and booleans are not credentials anyone could recognise in a log.
}
// Collect only string values, including those nested in lists and structs

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Applied in 43376e6.

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; it stops Log4j itself once it
has stopped, so what goes wrong while stopping is still logged.
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.
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_agent: service framework (Java)

2 participants