You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hudi.apache.org by vh...@apache.org on 2026/07/23 03:26:49 UTC
(hudi) branch master updated: feat: agentic lakehouse v1 - hudi-lakehouse charts and hudi-agent-gateway (#19265)
This is an automated email from the ASF dual-hosted git repository.
voonhous pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hudi.git
The following commit(s) were added to refs/heads/master by this push:
new a44829aa6ed9 feat: agentic lakehouse v1 - hudi-lakehouse charts and hudi-agent-gateway (#19265)
a44829aa6ed9 is described below
commit a44829aa6ed99f29847432536d6b7ec160e99720
Author: vinoth chandar <vi...@users.noreply.github.com>
AuthorDate: Wed Jul 22 20:26:42 2026 -0700
feat: agentic lakehouse v1 - hudi-lakehouse charts and hudi-agent-gateway (#19265)
* feat: add hudi-k8s-lakehouse - hudi-trino Helm chart and local-dev Kubernetes environment
Kubernetes packaging for the Hudi lakehouse, split by concern:
- charts/hudi-trino: a deployable product chart - Trino (server 472, pinned by
the hudi-trino-plugin's strict SPI check) with the Hudi connector built from
this repository. Values point at existing infrastructure: Hive Metastore
(thrift) or AWS Glue, S3/GCS via Trino's native filesystem; credentials via
Secret-backed env substitution, never in ConfigMaps.
- local-dev/: a minikube developer environment that stands up what the chart
points at - MinIO, a Derby-backed Hive Metastore (stock apache/hive image
configured entirely via manifest: single-authority schema init, Recreate
strategy for the Derby singleton, HADOOP_CLASSPATH for S3A as non-root) and
the Apache Spark Kubernetes Operator - then installs the same hudi-trino
chart with local values.
- local-dev/example/: a copy-me template for submitting any Spark job as a
SparkApplication; the sample writes a partitioned Hudi COW table to MinIO
and registers it in HMS via hive-sync, immediately queryable from Trino.
- images/ + scripts/: thin Dockerfiles over official images; jars staged from
local maven builds into gitignored target/ dirs (no binaries in git).
Tables Trino must read are written with hoodie.write.table.version=8 and
auto-upgrade disabled: the plugin currently reads with a Hudi 1.0.x runtime
(table versions 6/8). This pin is documented and goes away when the plugin's
Hudi dependency is upgraded.
Verified end to end on minikube from a clean cluster via
local-dev/scripts/smoke-test.sh: up -> Spark write+sync -> Trino serves 100
rows with correct partition aggregates.
* feat: add one-command idempotent quickstart for hudi-k8s-lakehouse
scripts/quickstart.sh converges the entire local-dev lakehouse in one run:
preflight -> minikube (started if absent) -> maven artifacts (spark bundle +
trino plugin; a Temurin JDK 23 is auto-provisioned into a gitignored .tools/
dir when none is installed) -> container images into minikube's docker
daemon -> MinIO + HMS + Spark Operator + hudi-trino chart. Every step checks
whether its work is already done, so re-running is always safe;
--run-example additionally runs the example Spark job so a Hudi table is
registered and ready to query from Trino. --rebuild-jars/--rebuild-images
force refreshes.
up.sh made fully idempotent (immutable bucket Job deleted before re-apply);
README restructured around the one-command path with a scripts reference
table.
Verified: quickstart.sh --run-example green on an already-provisioned
machine (all builds skipped, releases converged, example re-ran, Trino
served correct results).
* feat: add hudi-ai-gateway - the lakehouse AI serving layer (agent loop, MCP server, chat UI)
A new top-level Python service module implementing 'Surface 5' of the
AI-native lakehouse: ONE deployable process serving the lakehouse to AI.
Three surfaces over one guarded tool set:
- POST /v1/chat: the agent loop (LangGraph ReAct over lakehouse tools) with
multi-turn sessions (checkpointer-backed, TTL/LRU-bounded in-memory store)
and SSE streaming (token / tool_call / tool_result / done / error events).
- /mcp: an MCP server (streamable HTTP) exposing the same tools to external
agents such as Claude; tools are defined once and derived for both the
agent loop and MCP from a single registry, with every invocation logged as
structured JSON (the seed of the gateway's trace collection).
- /ui: a first-party ChatGPT-style chat UI (vanilla JS/CSS, zero third-party
code - no CDN, no npm, license-clean and air-gap friendly) with streamed
tokens, collapsible tool-activity chips, and markdown table rendering.
Pluggable LLM providers selected by config: anthropic, openai, ollama (local
laptop default), and openai-compatible endpoints (vLLM etc.). Construction
never touches the network; /ready reports per-dependency status (trino, llm)
and gates the Kubernetes readiness probe.
v1 tools query Trino: query_lakehouse (AST-level guardrails via sqlglot -
single-statement, SELECT-only, fail-closed parse, row cap injected as LIMIT,
result truncation with explicit notice), list_tables and describe_table via
information_schema (works for thrift HMS and Glue alike).
Deployment: charts/hudi-ai-gateway (sibling of hudi-trino, same conventions;
API keys via Secret/existingSecret only; replicas pinned to 1 for the
in-memory session store) wired into local-dev up.sh (default ON, no --wait
since readiness reflects LLM reachability) and build-images.sh/quickstart.sh.
Verified: 74 offline tests (fake Trino + scripted model through the real
create_react_agent), ruff + mypy clean; live end-to-end on the local-dev
stack with both anthropic (claude-haiku-4-5) and fully-local ollama
(qwen3:4b) - grounded answers with correct counts from hudi.default.trips,
guardrail LIMIT visible in executed SQL, browser-verified chat UI, MCP
initialize over HTTP; in-cluster e2e green (pod Ready with trino + host
ollama checks, chat through the k8s service).
* feat: provider-aware model selection, standard secret convention, and optional vllm chart
Out-of-box experience stays Ollama everywhere; switching providers is a
values change; and the UI now adapts to whatever the deployment is
configured with:
- GET /v1/models discovers the configured provider's models LIVE (Anthropic
and OpenAI model APIs, Ollama's local tags, vLLM's served models; 60s
cache; falls back to the configured default when listing fails).
- POST /v1/chat accepts an optional 'model' (within the provider); agents
are built lazily per model and share the session checkpointer, so
conversations survive model switches.
- The chat UI gains a model picker fed by /v1/models (persisted per
browser; single-model deployments like vLLM render it disabled).
- Chart secrets standardized: the deployment mounts one Secret via envFrom
and keys use the providers' standard env-var names (ANTHROPIC_API_KEY,
OPENAI_API_KEY; future TOGETHER_API_KEY/FIREWORKS_API_KEY/BASETEN_API_KEY/
HF_TOKEN need no chart changes). Compatible with External Secrets/Vault
CSI via existingSecret.
- New optional charts/vllm: vLLM (v0.25.0) serving one open-weight model
behind an OpenAI-compatible API; ungated Qwen/Qwen3-8B default (no HF
token needed), tool-calling flags preconfigured, model-cache PVC, GPU
resources, generous startup probe. INSTALL_VLLM=1 in local-dev up.sh
installs it and points the gateway at it (VLLM_MODEL= to override).
GPU-only: verified via helm lint/template, not a live pod.
Verified: 78 offline tests + ruff + mypy; live /v1/models against Anthropic
(real model list) and per-request model switch (claude-sonnet-5) answering
from the trips table; UI picker rendered in browser; both charts lint.
* chore: cache the gateway image's dependency layer across source changes
Install deps against a stub package first, then overlay real sources with a
no-deps reinstall - source edits no longer re-download the dependency tree.
* feat: connect panel in the gateway UI - one place for all lakehouse endpoints
/v1/info now reports the configured Trino URL and MCP state; the UI gains a
'Connect' panel listing the three ways into the lakehouse with
copy-to-clipboard: the Trino SQL endpoint (for any SQL client/BI tool), the
inference API (POST /v1/chat), and the MCP server URL (with the
claude mcp add snippet). Makes the chat UI the single pane of glass for the
whole stack.
* refactor: rename modules for the agentic-lakehouse positioning
- hudi-k8s-lakehouse/ -> hudi-lakehouse/ (the distribution is the product;
Kubernetes is the deployment target, not the identity)
- hudi-ai-gateway/ -> hudi-agent-gateway/ (module, python package, chart,
CLI, image name). 'AI gateway' now names a specific infra category -- LLM
proxy/routers -- which this is not: the server HOSTS the agent and gateways
external agents into the lakehouse via MCP. 'agent-gateway' reads correctly
in both directions.
Mechanical rename: no behavior changes. All references swept (python package
hudi_agent_gateway, pyproject/console script, chart names + helpers, image
hudi-lakehouse-agent-gateway, scripts incl. INSTALL_AGENT_GATEWAY toggle,
READMEs, UI display strings). Verified: 78 tests + ruff + mypy green in a
fresh venv; all three charts lint; scripts syntax-checked; zero stale
references.
* fix: repair streamed adaptive-thinking blocks in the agent loop
Anthropic's adaptive-thinking models (claude-fable-5, claude-opus-4-8) can
return a thinking block whose text is empty (signature only). When such a
turn is streamed, langchain-anthropic (<=1.4.8) merges the chunks into a
block with no 'thinking' key at all, and the API rejects the message on the
next agent-loop call with 'thinking.thinking: Field required' -- so every
tool-using conversation on a thinking model died on turn two, while
non-thinking models (haiku) worked.
Work around it in the pre-model hook: restore the empty 'thinking' field on
affected blocks before each model call (lossless; copies the message rather
than mutating checkpointed history). Verified live: opus-4-8 and fable-5 now
complete multi-round tool loops over SSE.
* chore: add GitHub Actions CI for hudi-agent-gateway and lakehouse charts
The Python gateway module and the Helm charts were previously untested in
CI. Adds a path-filtered workflow that runs the offline pytest suite (80
tests, no live LLM/Trino needed), ruff, and mypy on Python 3.11 and 3.12,
plus helm lint/template over every chart (hudi-trino renders with local-dev
values since its defaults fail fast on the required metastore uri).
* fix: rename 'New chat' to 'Clear chat' in the gateway UI
The button clears the message list and rotates the session id; nothing is
persisted, so 'New chat' over-promised. Session/chat persistence is tracked
as follow-on work.
* fix: make UI example prompts catalog-agnostic
The welcome suggestions referenced the local-dev demo 'trips' table; phrase
them so the agent's own catalog introspection adapts them to whatever tables
exist.
* feat: add Trino web UI to connect panel, raise default SQL timeout to 120s
Load-testing against ~60M rows surfaced both: the connect panel had no link
to Trino's own UI for watching queries run, and analytical aggregations can
legitimately exceed 60s on small clusters. Also give timed-out queries an
actionable hint (narrow the query or raise GATEWAY_SQL_TIMEOUT_SECONDS)
instead of the misleading 'Fix the SQL' -- the SQL was fine.
* fix: satisfy release source-license validation for new module files
validate_source_copyright.sh flagged four files from the new modules:
.helmignore, .dockerignore, and py.typed now carry the ASF header (PEP 561
ignores py.typed content, so the marker stays valid -- mypy verified), and
.png joins .jpg in the script's binary exemptions for the gateway UI logo.
With the header inside py.typed the rat exclude added earlier in this branch
is unnecessary; the root pom.xml is back to fully untouched.
* fix: use preinstalled helm in agent gateway CI
azure/setup-helm is not on the apache org's Actions allowlist and
startup-failed the whole workflow; GitHub-hosted ubuntu runners ship helm
preinstalled, so the third-party action is unnecessary. Remaining actions
(checkout, setup-python) are GitHub-created and allowlisted.
* fix: address review feedback on tool input validation and result sizing
- list_tables/describe_table interpolated catalog/schema/table names into
SQL unvalidated; these arrive over HTTP and MCP, so quoted values could
break out of the identifier/literal. Names are now validated against a
strict identifier pattern and rejected with a hint before any SQL is built.
- shape_result could exceed the configured size cap even after dropping all
rows (huge sql text / many columns / tiny cap); it now degrades to a
bounded metadata payload, and past that to a bare error payload.
- README documented the old 60s default for GATEWAY_SQL_TIMEOUT_SECONDS;
now matches the 120s code default.
* fix: address second-round review feedback on gateway robustness and quickstart
- llm.py: wire GATEWAY_LLM_TIMEOUT_SECONDS into the default (ollama)
provider via httpx client_kwargs, so a stalled Ollama no longer hangs
/v1/chat unboundedly
- chat.py/registry.py: replace the substring-based tool-error detection
with a shared JSON-parsing is_tool_error(); a successful result with a
column named "error" is no longer reported as a failed tool call
- trino_tools.py: results that fill the row cap now report
truncated: true with a notice, so the agent warns instead of
presenting a capped answer as complete
- trino_client.py: queries run on a dedicated bounded executor and the
timeout path cancels the Trino query server-side, so repeated
timeouts cannot pile up stuck threads; /ready's SELECT 1 ping is now
cached (10s) like the LLM check
- gateway chart: explicit readinessProbe timeoutSeconds (k8s' 1s
default flapped against the check's own multi-second budget)
- build-jars.sh: the JDK-23 guard probes the JDK Maven will actually
use (honours JAVA_HOME) instead of PATH's java, unbreaking the
one-command quickstart on machines whose default JDK is older
- quickstart/build scripts: drop the --spark-version flag; the
quickstart supports exactly the Spark 3.5 line the example manifest
pins, so a 4.1 image that nothing templates can no longer be selected
- UI: hotlink the logo from hudi.apache.org (no vendored binary) and revert the repo-wide *.png
exemption added to validate_source_copyright.sh
- README: document that v1 ships with no authn/authz
- registry.py: narrow input_schema derivation to pydantic v2 models
(newer langchain-core widened tool_call_schema's type; mypy)
- guardrails: add a SELECT-rooted rejection test (CTE wrapping INSERT)
so the defense-in-depth tree walk is actually exercised
---
.github/workflows/agent_gateway_ci.yml | 91 +++++++
hudi-agent-gateway/.dockerignore | 25 ++
hudi-agent-gateway/.gitignore | 9 +
hudi-agent-gateway/Dockerfile | 38 +++
hudi-agent-gateway/README.md | 134 +++++++++++
hudi-agent-gateway/pyproject.toml | 89 +++++++
.../src/hudi_agent_gateway/__init__.py | 24 ++
.../src/hudi_agent_gateway/__main__.py | 20 ++
hudi-agent-gateway/src/hudi_agent_gateway/agent.py | 155 ++++++++++++
.../src/hudi_agent_gateway/api/__init__.py | 15 ++
.../src/hudi_agent_gateway/api/chat.py | 204 ++++++++++++++++
.../src/hudi_agent_gateway/api/meta.py | 99 ++++++++
.../src/hudi_agent_gateway/api/models.py | 112 +++++++++
hudi-agent-gateway/src/hudi_agent_gateway/app.py | 97 ++++++++
hudi-agent-gateway/src/hudi_agent_gateway/cli.py | 52 ++++
.../src/hudi_agent_gateway/config.py | 93 +++++++
hudi-agent-gateway/src/hudi_agent_gateway/llm.py | 177 ++++++++++++++
hudi-agent-gateway/src/hudi_agent_gateway/log.py | 71 ++++++
.../src/hudi_agent_gateway/mcp_server.py | 41 ++++
hudi-agent-gateway/src/hudi_agent_gateway/py.typed | 15 ++
.../src/hudi_agent_gateway/sessions.py | 84 +++++++
.../src/hudi_agent_gateway/tools/__init__.py | 37 +++
.../src/hudi_agent_gateway/tools/guardrails.py | 92 +++++++
.../src/hudi_agent_gateway/tools/registry.py | 158 ++++++++++++
.../src/hudi_agent_gateway/tools/trino_client.py | 123 ++++++++++
.../src/hudi_agent_gateway/tools/trino_tools.py | 231 ++++++++++++++++++
.../src/hudi_agent_gateway/ui/app.js | 268 +++++++++++++++++++++
.../src/hudi_agent_gateway/ui/index.html | 105 ++++++++
.../src/hudi_agent_gateway/ui/markdown.js | 130 ++++++++++
.../src/hudi_agent_gateway/ui/style.css | 260 ++++++++++++++++++++
hudi-agent-gateway/tests/conftest.py | 147 +++++++++++
hudi-agent-gateway/tests/integration/__init__.py | 15 ++
.../tests/integration/test_live_stack.py | 93 +++++++
hudi-agent-gateway/tests/test_agent_loop.py | 143 +++++++++++
hudi-agent-gateway/tests/test_api_meta.py | 93 +++++++
hudi-agent-gateway/tests/test_chat_sse.py | 134 +++++++++++
hudi-agent-gateway/tests/test_config.py | 76 ++++++
hudi-agent-gateway/tests/test_guardrails.py | 104 ++++++++
hudi-agent-gateway/tests/test_llm.py | 114 +++++++++
hudi-agent-gateway/tests/test_mcp.py | 78 ++++++
hudi-agent-gateway/tests/test_registry.py | 100 ++++++++
hudi-agent-gateway/tests/test_sessions.py | 68 ++++++
hudi-agent-gateway/tests/test_trino_tools.py | 134 +++++++++++
hudi-agent-gateway/tests/test_ui.py | 77 ++++++
hudi-lakehouse/.gitignore | 5 +
hudi-lakehouse/README.md | 128 ++++++++++
.../charts/hudi-agent-gateway/Chart.yaml | 34 +++
.../charts/hudi-agent-gateway/templates/NOTES.txt | 46 ++++
.../hudi-agent-gateway/templates/_helpers.tpl | 52 ++++
.../hudi-agent-gateway/templates/deployment.yaml | 135 +++++++++++
.../hudi-agent-gateway/templates/secret.yaml | 35 +++
.../hudi-agent-gateway/templates/service.yaml | 29 +++
.../hudi-agent-gateway/values-local-dev.yaml | 41 ++++
.../charts/hudi-agent-gateway/values.yaml | 94 ++++++++
hudi-lakehouse/charts/hudi-trino/.helmignore | 24 ++
hudi-lakehouse/charts/hudi-trino/Chart.yaml | 32 +++
.../charts/hudi-trino/templates/NOTES.txt | 32 +++
.../charts/hudi-trino/templates/_helpers.tpl | 52 ++++
.../hudi-trino/templates/configmap-catalog.yaml | 58 +++++
.../charts/hudi-trino/templates/deployment.yaml | 90 +++++++
.../charts/hudi-trino/templates/secret.yaml | 28 +++
.../charts/hudi-trino/templates/service.yaml | 29 +++
.../charts/hudi-trino/values-local-dev.yaml | 41 ++++
hudi-lakehouse/charts/hudi-trino/values.yaml | 83 +++++++
hudi-lakehouse/charts/vllm/Chart.yaml | 32 +++
hudi-lakehouse/charts/vllm/templates/NOTES.txt | 32 +++
hudi-lakehouse/charts/vllm/templates/_helpers.tpl | 43 ++++
.../charts/vllm/templates/deployment.yaml | 102 ++++++++
hudi-lakehouse/charts/vllm/templates/pvc.yaml | 31 +++
hudi-lakehouse/charts/vllm/templates/service.yaml | 29 +++
hudi-lakehouse/charts/vllm/values.yaml | 86 +++++++
hudi-lakehouse/images/spark/Dockerfile | 42 ++++
hudi-lakehouse/images/trino/Dockerfile | 33 +++
hudi-lakehouse/local-dev/README.md | 71 ++++++
hudi-lakehouse/local-dev/example/README.md | 55 +++++
.../local-dev/example/hudi_table_writer.py | 87 +++++++
hudi-lakehouse/local-dev/example/spark-app.yaml | 61 +++++
.../local-dev/manifests/hive-metastore.yaml | 196 +++++++++++++++
.../local-dev/manifests/minio-bucket-job.yaml | 45 ++++
hudi-lakehouse/local-dev/manifests/minio.yaml | 96 ++++++++
hudi-lakehouse/local-dev/manifests/namespace.yaml | 21 ++
hudi-lakehouse/local-dev/scripts/down.sh | 29 +++
hudi-lakehouse/local-dev/scripts/run-example.sh | 90 +++++++
hudi-lakehouse/local-dev/scripts/smoke-test.sh | 46 ++++
hudi-lakehouse/local-dev/scripts/up.sh | 96 ++++++++
hudi-lakehouse/scripts/build-images.sh | 86 +++++++
hudi-lakehouse/scripts/build-jars.sh | 63 +++++
hudi-lakehouse/scripts/quickstart.sh | 165 +++++++++++++
88 files changed, 7130 insertions(+)
diff --git a/.github/workflows/agent_gateway_ci.yml b/.github/workflows/agent_gateway_ci.yml
new file mode 100644
index 000000000000..1a9cd3b973a2
--- /dev/null
+++ b/.github/workflows/agent_gateway_ci.yml
@@ -0,0 +1,91 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+name: Agent Gateway CI
+
+on:
+ push:
+ branches:
+ - master
+ - 'release-*'
+ paths:
+ - 'hudi-agent-gateway/**'
+ - 'hudi-lakehouse/**'
+ - '.github/workflows/agent_gateway_ci.yml'
+ pull_request:
+ branches:
+ - master
+ paths:
+ - 'hudi-agent-gateway/**'
+ - 'hudi-lakehouse/**'
+ - '.github/workflows/agent_gateway_ci.yml'
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+permissions:
+ contents: read
+
+jobs:
+ gateway-tests:
+ name: gateway pytest + lint (python ${{ matrix.python }})
+ runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ python: ['3.11', '3.12']
+ defaults:
+ run:
+ working-directory: hudi-agent-gateway
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-python@v5
+ with:
+ python-version: ${{ matrix.python }}
+ cache: pip
+ cache-dependency-path: hudi-agent-gateway/pyproject.toml
+ - name: Install
+ run: pip install -e ".[dev]"
+ - name: Test
+ run: python -m pytest tests -q
+ - name: Lint
+ run: ruff check src tests
+ - name: Type-check
+ run: mypy src
+
+ chart-lint:
+ name: helm lint + template
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ # helm is preinstalled on GitHub-hosted ubuntu runners. Do NOT add
+ # azure/setup-helm or other third-party actions here: the apache org
+ # allowlist only permits GitHub-created actions (actions/*) and a
+ # curated set, and anything else startup-fails the whole workflow.
+ - name: Lint charts
+ run: |
+ # hudi-trino intentionally fails fast on default values (metastore
+ # uri is required), so render with local-dev values when present.
+ for chart in hudi-lakehouse/charts/*/; do
+ helm lint "$chart"
+ if [ -f "$chart/values-local-dev.yaml" ]; then
+ helm lint "$chart" -f "$chart/values-local-dev.yaml"
+ helm template "$chart" -f "$chart/values-local-dev.yaml" > /dev/null
+ else
+ helm template "$chart" > /dev/null
+ fi
+ done
diff --git a/hudi-agent-gateway/.dockerignore b/hudi-agent-gateway/.dockerignore
new file mode 100644
index 000000000000..22ee45d596d8
--- /dev/null
+++ b/hudi-agent-gateway/.dockerignore
@@ -0,0 +1,25 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+.venv
+__pycache__
+*.egg-info
+dist
+build
+.pytest_cache
+.ruff_cache
+.mypy_cache
+tests
\ No newline at end of file
diff --git a/hudi-agent-gateway/.gitignore b/hudi-agent-gateway/.gitignore
new file mode 100644
index 000000000000..95e8001f233e
--- /dev/null
+++ b/hudi-agent-gateway/.gitignore
@@ -0,0 +1,9 @@
+.venv/
+__pycache__/
+*.egg-info/
+dist/
+build/
+.pytest_cache/
+.ruff_cache/
+.mypy_cache/
+.coverage
diff --git a/hudi-agent-gateway/Dockerfile b/hudi-agent-gateway/Dockerfile
new file mode 100644
index 000000000000..27fae43b0ce6
--- /dev/null
+++ b/hudi-agent-gateway/Dockerfile
@@ -0,0 +1,38 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# The hudi-agent-gateway server image. Build context: this directory.
+FROM python:3.12-slim
+
+RUN groupadd --gid 1000 gateway && \
+ useradd --uid 1000 --gid gateway --create-home gateway
+
+WORKDIR /opt/hudi-agent-gateway
+# Install third-party dependencies in their own layer (cached across source
+# changes) by building against a stub package first, then overlay the real
+# sources with a fast no-deps reinstall.
+COPY pyproject.toml README.md ./
+RUN mkdir -p src/hudi_agent_gateway \
+ && printf '__version__ = "0.1.0"\n' > src/hudi_agent_gateway/__init__.py \
+ && pip install --no-cache-dir . \
+ && pip uninstall -y hudi-agent-gateway
+COPY src ./src
+RUN pip install --no-cache-dir --no-deps .
+
+USER gateway
+EXPOSE 8000
+ENTRYPOINT ["hudi-agent-gateway"]
+CMD ["serve"]
diff --git a/hudi-agent-gateway/README.md b/hudi-agent-gateway/README.md
new file mode 100644
index 000000000000..d1ca1c2435c6
--- /dev/null
+++ b/hudi-agent-gateway/README.md
@@ -0,0 +1,134 @@
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+# hudi-agent-gateway
+
+**One deployable service that serves your Hudi lakehouse to AI.** A single
+process hosts three surfaces over the same set of guarded lakehouse tools:
+
+| Surface | Where | What |
+|---|---|---|
+| Agent chat API | `POST /v1/chat` | prompt in → LangGraph agent loop (model ↔ tools) → grounded answer out; multi-turn sessions; optional SSE streaming |
+| MCP server | `/mcp` (streamable HTTP) | external agents (Claude, anything MCP) call the lakehouse tools directly |
+| Chat UI | `/ui/` | first-party ChatGPT-style web UI (zero third-party code) |
+
+The v1 tools query the lakehouse through Trino: `query_lakehouse` (guarded,
+read-only SQL), `list_tables`, `describe_table`. Every model-written query
+passes AST-level guardrails (single statement, SELECT-only, row cap injected
+as a real `LIMIT`) and every invocation is logged as structured JSON — the
+seed of the gateway's trace collection.
+
+## Quickstart (local process)
+
+```bash
+cd hudi-agent-gateway
+python3.12 -m venv .venv && .venv/bin/pip install -e ".[dev]"
+
+# point at a Trino with the Hudi connector (e.g. the local-dev stack, port-forwarded):
+GATEWAY_TRINO_HOST=localhost GATEWAY_TRINO_PORT=18080 \
+GATEWAY_LLM_PROVIDER=anthropic GATEWAY_LLM_MODEL=claude-haiku-4-5-20251001 \
+ .venv/bin/hudi-agent-gateway serve
+
+curl -X POST localhost:8000/v1/chat -H 'Content-Type: application/json' \
+ -d '{"message": "How many trips per city?", "session_id": "s1"}'
+open http://localhost:8000/ui/
+```
+
+`GET /v1/models` lists the models the configured provider offers (live:
+Anthropic and OpenAI model APIs, Ollama's local tags, vLLM's served models),
+and `POST /v1/chat` accepts an optional `"model"` to pick one per request —
+the chat UI exposes this as a model picker. Sessions survive model switches.
+
+For a fully local model, install [Ollama](https://ollama.com), pull a
+tool-capable model, and use the default provider:
+
+```bash
+ollama pull qwen3:8b
+GATEWAY_LLM_PROVIDER=ollama GATEWAY_LLM_MODEL=qwen3:8b hudi-agent-gateway serve
+```
+
+Connect an MCP client:
+
+```bash
+claude mcp add --transport http hudi-lakehouse http://localhost:8000/mcp/
+```
+
+## Deploying on Kubernetes
+
+See `hudi-lakehouse/charts/hudi-agent-gateway` — the product Helm chart —
+and `hudi-lakehouse/local-dev/` for a complete laptop environment
+(MinIO + Hive Metastore + Trino + this gateway) where the gateway is
+installed alongside Trino by default.
+
+## Configuration
+
+Environment variables (prefix `GATEWAY_` except the standard key names):
+
+| Variable | Default | Purpose |
+|---|---|---|
+| `GATEWAY_LLM_PROVIDER` | `ollama` | `anthropic` \| `openai` \| `ollama` \| `openai-compatible` |
+| `GATEWAY_LLM_MODEL` | `qwen3:8b` | model name for the provider |
+| `ANTHROPIC_API_KEY` / `OPENAI_API_KEY` | — | required by the matching provider |
+| `GATEWAY_OLLAMA_BASE_URL` | `http://localhost:11434` | Ollama endpoint |
+| `GATEWAY_OPENAI_BASE_URL` | — | endpoint for `openai-compatible` (vLLM, Together, …) |
+| `GATEWAY_LLM_TIMEOUT_SECONDS` | `120` | per-model-call timeout |
+| `GATEWAY_TRINO_HOST` / `_PORT` | `hudi-trino.hudi-lakehouse.svc` / `8080` | Trino coordinator |
+| `GATEWAY_TRINO_CATALOG` / `_SCHEMA` / `_USER` | `hudi` / `default` / `hudi-agent-gateway` | query defaults |
+| `GATEWAY_SQL_ROW_CAP` | `200` | LIMIT enforced on every query |
+| `GATEWAY_SQL_TIMEOUT_SECONDS` | `120` | per-query timeout |
+| `GATEWAY_TOOL_RESULT_MAX_BYTES` | `50000` | tool results truncated beyond this (with notice) |
+| `GATEWAY_AGENT_MAX_ITERATIONS` | `25` | agent loop recursion limit |
+| `GATEWAY_SESSION_TTL_SECONDS` / `GATEWAY_MAX_SESSIONS` | `3600` / `1000` | session store bounds |
+| `GATEWAY_MAX_MESSAGES_PER_SESSION` | `40` | context window per session (trimmed pre-model) |
+| `GATEWAY_SYSTEM_PROMPT_EXTRA` | — | appended to the built-in system prompt |
+| `GATEWAY_MCP_ENABLED` | `true` | serve /mcp |
+| `GATEWAY_HOST` / `GATEWAY_PORT` / `GATEWAY_LOG_LEVEL` | `0.0.0.0` / `8000` / `INFO` | server basics |
+
+Startup never depends on the LLM or Trino being reachable: `/health` is
+liveness, `/ready` reports per-dependency status (and gates the Kubernetes
+readiness probe).
+
+## Development
+
+```bash
+.venv/bin/pytest # offline suite (fake Trino + scripted model)
+.venv/bin/ruff check src tests
+.venv/bin/mypy src
+
+# live integration (against a port-forwarded local-dev stack):
+GATEWAY_IT_TRINO_HOST=localhost GATEWAY_IT_TRINO_PORT=18080 .venv/bin/pytest tests/integration
+```
+
+Adding a tool: write a module under `src/hudi_agent_gateway/tools/` with a
+`register(registry, ...)` function and call it from
+`tools/__init__.py:build_registry`. One registration exposes it to the agent
+loop, the MCP server, `GET /v1/tools`, and the invocation log.
+
+## Design notes & limits (v1)
+
+- **No authentication in v1**: `/v1/chat`, `/mcp` and the other endpoints are
+ open to anyone who can reach the pod (and `GATEWAY_HOST` defaults to
+ `0.0.0.0`). Deploy behind an authenticating proxy or on a trusted network.
+- **Single replica**: sessions live in an in-memory LangGraph checkpointer.
+ The seam for horizontal scale is swapping in
+ `langgraph-checkpoint-postgres` inside `sessions.py`.
+- **Read-only by construction**: non-SELECT statements are rejected at the
+ AST level (sqlglot, fail-closed); `EXPLAIN` is also blocked in v1.
+- The chat UI is deliberately first-party and dependency-free (no CDN, no
+ npm) so the whole service works air-gapped and stays license-clean. The
+ one remote reference is the Hudi logo image, hotlinked from
+ hudi.apache.org; offline it degrades to alt text.
diff --git a/hudi-agent-gateway/pyproject.toml b/hudi-agent-gateway/pyproject.toml
new file mode 100644
index 000000000000..8b548f2e5271
--- /dev/null
+++ b/hudi-agent-gateway/pyproject.toml
@@ -0,0 +1,89 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+[build-system]
+requires = ["setuptools>=68"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "hudi-agent-gateway"
+description = "The Apache Hudi AI gateway: agent loop, MCP server, and chat UI over lakehouse tools"
+readme = "README.md"
+requires-python = ">=3.11"
+license = "Apache-2.0"
+dynamic = ["version"]
+dependencies = [
+ "fastapi>=0.115",
+ "uvicorn[standard]>=0.30",
+ "langgraph>=1.0,<2",
+ "langchain-core>=1.0,<2",
+ "langchain-anthropic>=1.0",
+ "langchain-openai>=1.0",
+ "langchain-ollama>=1.0",
+ "fastmcp>=2.10,<3",
+ "trino>=0.330",
+ "sqlglot>=25.0",
+ "pydantic>=2.7",
+ "pydantic-settings>=2.3",
+ "sse-starlette>=2.1",
+ "httpx>=0.27",
+]
+
+[project.optional-dependencies]
+dev = [
+ "pytest>=8.0",
+ "pytest-asyncio>=0.24",
+ "ruff>=0.6",
+ "mypy>=1.11",
+]
+
+[project.scripts]
+hudi-agent-gateway = "hudi_agent_gateway.cli:main"
+
+[project.urls]
+Homepage = "https://hudi.apache.org"
+Source = "https://github.com/apache/hudi"
+
+[tool.setuptools.dynamic]
+version = { attr = "hudi_agent_gateway.__version__" }
+
+[tool.setuptools.packages.find]
+where = ["src"]
+
+[tool.setuptools.package-data]
+hudi_agent_gateway = ["py.typed", "ui/*"]
+
+[tool.ruff]
+line-length = 100
+target-version = "py311"
+
+[tool.ruff.lint]
+select = ["E", "F", "W", "I", "UP", "B", "SIM", "ASYNC"]
+# ASYNC109: `timeout` parameters are part of the tool-facing contract here;
+# enforcement uses asyncio.wait_for internally.
+ignore = ["ASYNC109"]
+
+[tool.mypy]
+python_version = "3.11"
+strict = false
+check_untyped_defs = true
+warn_unused_ignores = true
+no_implicit_optional = true
+ignore_missing_imports = true
+
+[tool.pytest.ini_options]
+asyncio_mode = "auto"
+testpaths = ["tests"]
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/__init__.py b/hudi-agent-gateway/src/hudi_agent_gateway/__init__.py
new file mode 100644
index 000000000000..b82396d09e71
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/__init__.py
@@ -0,0 +1,24 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""The Apache Hudi agent gateway.
+
+One deployable service that serves the lakehouse to AI: a LangGraph agent
+loop over guarded lakehouse tools (Trino), an MCP server exposing the same
+tools to external agents, and a chat UI -- all in a single process.
+"""
+
+__version__ = "0.1.0"
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/__main__.py b/hudi-agent-gateway/src/hudi_agent_gateway/__main__.py
new file mode 100644
index 000000000000..d88140707418
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/__main__.py
@@ -0,0 +1,20 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from hudi_agent_gateway.cli import main
+
+if __name__ == "__main__":
+ main()
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/agent.py b/hudi-agent-gateway/src/hudi_agent_gateway/agent.py
new file mode 100644
index 000000000000..eb2add9873ff
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/agent.py
@@ -0,0 +1,155 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""The lakehouse agent: a LangGraph ReAct loop over the tool registry."""
+
+from __future__ import annotations
+
+from typing import Any, TypeGuard
+
+from langchain_core.language_models.chat_models import BaseChatModel
+from langchain_core.messages import AIMessage, AnyMessage, trim_messages
+from langchain_core.messages.utils import count_tokens_approximately
+from langgraph.checkpoint.base import BaseCheckpointSaver
+from langgraph.prebuilt import create_react_agent
+
+from hudi_agent_gateway.config import GatewaySettings
+from hudi_agent_gateway.tools.registry import ToolRegistry
+
+_SYSTEM_PROMPT = """\
+You are the Apache Hudi lakehouse analyst. You answer questions about data in \
+an Apache Hudi lakehouse by querying it through Trino using your tools. The \
+default catalog is `{catalog}` and the default schema is `{schema}`; tables \
+are Hudi tables registered in the catalog's metastore.
+
+Tool strategy:
+- For unfamiliar tables, call `list_tables` and `describe_table` BEFORE writing SQL.
+- `query_lakehouse` accepts exactly ONE read-only SELECT statement (Trino SQL). \
+Qualify names as catalog.schema.table when querying outside the defaults.
+- A server-side row cap of {row_cap} rows is enforced. Prefer aggregations, \
+GROUP BY, and explicit LIMIT over raw row dumps.
+- If a result has `truncated: true`, tell the user the result was truncated and \
+suggest how to narrow the query.
+- If a query fails, read the error, fix the SQL, and retry (at most two retries).
+
+Grounding rules:
+- Answer ONLY from tool results. Never invent table names, column names, or values.
+- State row counts when reporting results.
+- Be concise. Use markdown tables for tabular answers.
+{extra}"""
+
+
+def build_system_prompt(settings: GatewaySettings) -> str:
+ extra = f"\n{settings.system_prompt_extra}" if settings.system_prompt_extra else ""
+ return _SYSTEM_PROMPT.format(
+ catalog=settings.trino_catalog,
+ schema=settings.trino_schema,
+ row_cap=settings.sql_row_cap,
+ extra=extra,
+ )
+
+
+class AgentCache:
+ """Lazily builds one agent per model name (all sharing the same tools,
+ checkpointer, and prompt), so a deployment configured with one provider
+ can still serve any of that provider's models per request."""
+
+ _MAX_AGENTS = 8
+
+ def __init__(self, registry: ToolRegistry, checkpointer: BaseCheckpointSaver,
+ settings: GatewaySettings) -> None:
+ self._registry = registry
+ self._checkpointer = checkpointer
+ self._settings = settings
+ self._agents: dict[str, Any] = {}
+
+ def get(self, model: str | None = None) -> Any:
+ from hudi_agent_gateway.llm import build_chat_model
+
+ name = model or self._settings.llm_model
+ if name not in self._agents:
+ if len(self._agents) >= self._MAX_AGENTS:
+ self._agents.pop(next(iter(self._agents)))
+ self._agents[name] = build_agent(
+ build_chat_model(self._settings, name),
+ self._registry,
+ self._checkpointer,
+ self._settings,
+ )
+ return self._agents[name]
+
+
+def _is_broken_thinking_block(block: Any) -> TypeGuard[dict[str, Any]]:
+ return isinstance(block, dict) and block.get("type") == "thinking" and "thinking" not in block
+
+
+def repair_thinking_blocks(messages: list[AnyMessage]) -> list[AnyMessage]:
+ """Restore the `thinking` field on streamed adaptive-thinking blocks.
+
+ Anthropic's adaptive-thinking models can return a thinking block whose text
+ is empty (signature only). When such a turn is streamed, langchain-anthropic
+ merges the chunks into a block with no `thinking` key at all, and the API
+ rejects the message on the next agent-loop call with
+ "thinking.thinking: Field required". Re-adding the empty field is lossless.
+ """
+ repaired: list[AnyMessage] = []
+ for msg in messages:
+ content = msg.content
+ if (
+ isinstance(msg, AIMessage)
+ and isinstance(content, list)
+ and any(_is_broken_thinking_block(b) for b in content)
+ ):
+ blocks = [
+ {**b, "thinking": ""} if _is_broken_thinking_block(b) else b
+ for b in content
+ ]
+ msg = msg.model_copy(update={"content": blocks})
+ repaired.append(msg)
+ return repaired
+
+
+def build_agent(
+ model: BaseChatModel,
+ registry: ToolRegistry,
+ checkpointer: BaseCheckpointSaver,
+ settings: GatewaySettings,
+) -> Any:
+ max_messages = settings.max_messages_per_session
+
+ def trim_llm_input(state: dict[str, Any]) -> dict[str, Any]:
+ # Bound what reaches the model without rewriting checkpointed history.
+ trimmed = trim_messages(
+ state["messages"],
+ strategy="last",
+ token_counter=len,
+ max_tokens=max_messages,
+ start_on="human",
+ include_system=True,
+ allow_partial=False,
+ )
+ return {"llm_input_messages": repair_thinking_blocks(trimmed)}
+
+ return create_react_agent(
+ model=model,
+ tools=registry.langchain_tools(),
+ prompt=build_system_prompt(settings),
+ checkpointer=checkpointer,
+ pre_model_hook=trim_llm_input,
+ )
+
+
+_ = count_tokens_approximately # re-exported for callers wanting token-based trimming later
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/api/__init__.py b/hudi-agent-gateway/src/hudi_agent_gateway/api/__init__.py
new file mode 100644
index 000000000000..c5a5d9fae9de
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/api/__init__.py
@@ -0,0 +1,15 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/api/chat.py b/hudi-agent-gateway/src/hudi_agent_gateway/api/chat.py
new file mode 100644
index 000000000000..08263e256155
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/api/chat.py
@@ -0,0 +1,204 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""POST /v1/chat: the agent-loop inference endpoint (JSON or SSE)."""
+
+from __future__ import annotations
+
+import logging
+import uuid
+from collections.abc import AsyncIterator
+from typing import Any
+
+from fastapi import APIRouter, HTTPException, Request
+from langchain_core.messages import AIMessage, AIMessageChunk, HumanMessage, ToolMessage
+from langgraph.errors import GraphRecursionError
+from sse_starlette.sse import EventSourceResponse, ServerSentEvent
+
+from hudi_agent_gateway.api.models import (
+ ChatRequest,
+ ChatResponse,
+ DoneEvent,
+ ErrorEvent,
+ TokenEvent,
+ ToolCallEvent,
+ ToolResultEvent,
+ ToolTraceEntry,
+)
+from hudi_agent_gateway.log import log_event, request_id_var, session_id_var
+from hudi_agent_gateway.tools.registry import is_tool_error
+
+logger = logging.getLogger("hudi_agent_gateway.chat")
+
+
+def _message_text(msg: Any) -> str:
+ text = getattr(msg, "text", None)
+ if callable(text): # langchain-core < 1.x compatibility
+ return text()
+ if isinstance(text, str):
+ return text
+ return str(getattr(msg, "content", ""))
+
+
+router = APIRouter()
+
+_PREVIEW_CHARS = 500
+
+
+def _agent_config(request: Request, session_id: str) -> dict[str, Any]:
+ settings = request.app.state.settings
+ return {
+ "configurable": {"thread_id": session_id},
+ "recursion_limit": settings.agent_max_iterations,
+ }
+
+
+def _tool_trace_from_messages(messages: list[Any]) -> list[ToolTraceEntry]:
+ """Reconstruct the tool trace from the messages appended this turn."""
+ calls: dict[str, ToolTraceEntry] = {}
+ trace: list[ToolTraceEntry] = []
+ for msg in messages:
+ if isinstance(msg, AIMessage):
+ for tc in msg.tool_calls or []:
+ entry = ToolTraceEntry(name=tc["name"], args=tc.get("args") or {})
+ calls[tc.get("id") or ""] = entry
+ trace.append(entry)
+ elif isinstance(msg, ToolMessage):
+ matched = calls.get(msg.tool_call_id or "")
+ if matched is not None:
+ content = msg.content if isinstance(msg.content, str) else str(msg.content)
+ matched.result_preview = content[:_PREVIEW_CHARS]
+ matched.is_error = is_tool_error(content)
+ return trace
+
+
+@router.post("/v1/chat")
+async def chat(request: Request, body: ChatRequest) -> Any:
+ request_id_var.set(uuid.uuid4().hex[:12])
+ session_id_var.set(body.session_id)
+ state = request.app.state
+ state.sessions.touch(body.session_id)
+ log_event(logger, "chat_request", stream=body.stream, message_chars=len(body.message))
+
+ wants_stream = body.stream or "text/event-stream" in request.headers.get("accept", "")
+ if wants_stream:
+ return EventSourceResponse(_stream_chat(request, body))
+
+ agent = state.agents.get(body.model)
+ inputs = {"messages": [HumanMessage(body.message)]}
+ try:
+ result = await agent.ainvoke(inputs, config=_agent_config(request, body.session_id))
+ except GraphRecursionError as e:
+ raise HTTPException(
+ status_code=422,
+ detail="The agent hit its iteration limit before finishing. Try a narrower question.",
+ ) from e
+ except Exception as e:
+ logger.exception("agent invocation failed")
+ raise HTTPException(status_code=502, detail=f"agent failed: {e}") from e
+
+ messages = result["messages"]
+ final = messages[-1]
+ final_text = _message_text(final)
+ # Trace only this turn: messages after the HumanMessage we just appended.
+ turn_start = max(
+ i for i, m in enumerate(messages) if isinstance(m, HumanMessage)
+ )
+ return ChatResponse(
+ session_id=body.session_id,
+ message=final_text,
+ tool_trace=_tool_trace_from_messages(messages[turn_start:]),
+ )
+
+
+async def _stream_chat(request: Request, body: ChatRequest) -> AsyncIterator[ServerSentEvent]:
+ state = request.app.state
+ agent = state.agents.get(body.model)
+ inputs = {"messages": [HumanMessage(body.message)]}
+ final_text_parts: list[str] = []
+ try:
+ async for mode, chunk in agent.astream(
+ inputs,
+ config=_agent_config(request, body.session_id),
+ stream_mode=["messages", "updates"],
+ ):
+ if mode == "messages":
+ msg_chunk, _meta = chunk
+ if isinstance(msg_chunk, AIMessageChunk):
+ text = _message_text(msg_chunk)
+ if text:
+ final_text_parts.append(text)
+ yield ServerSentEvent(
+ event="token", data=TokenEvent(text=text).model_dump_json()
+ )
+ elif mode == "updates" and isinstance(chunk, dict):
+ for events in _updates_to_events(chunk):
+ yield events
+ except GraphRecursionError:
+ yield ServerSentEvent(
+ event="error",
+ data=ErrorEvent(
+ code="recursion_limit",
+ message="The agent hit its iteration limit before finishing.",
+ ).model_dump_json(),
+ )
+ return
+ except Exception as e: # noqa: BLE001 - stream must terminate with an error event
+ logger.exception("agent stream failed")
+ yield ServerSentEvent(
+ event="error",
+ data=ErrorEvent(code="agent_error", message=str(e)).model_dump_json(),
+ )
+ return
+
+ yield ServerSentEvent(
+ event="done",
+ data=DoneEvent(
+ session_id=body.session_id, message="".join(final_text_parts)
+ ).model_dump_json(),
+ )
+
+
+def _updates_to_events(update: dict[str, Any]) -> list[ServerSentEvent]:
+ events: list[ServerSentEvent] = []
+ agent_update = update.get("agent") or {}
+ for msg in agent_update.get("messages", []):
+ if isinstance(msg, AIMessage):
+ for tc in msg.tool_calls or []:
+ events.append(
+ ServerSentEvent(
+ event="tool_call",
+ data=ToolCallEvent(
+ id=tc.get("id") or "", name=tc["name"], args=tc.get("args") or {}
+ ).model_dump_json(),
+ )
+ )
+ tools_update = update.get("tools") or {}
+ for msg in tools_update.get("messages", []):
+ if isinstance(msg, ToolMessage):
+ content = msg.content if isinstance(msg.content, str) else str(msg.content)
+ events.append(
+ ServerSentEvent(
+ event="tool_result",
+ data=ToolResultEvent(
+ id=msg.tool_call_id or "",
+ name=msg.name or "",
+ preview=content[:_PREVIEW_CHARS],
+ is_error=is_tool_error(content),
+ ).model_dump_json(),
+ )
+ )
+ return events
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/api/meta.py b/hudi-agent-gateway/src/hudi_agent_gateway/api/meta.py
new file mode 100644
index 000000000000..0273b7798859
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/api/meta.py
@@ -0,0 +1,99 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Operational endpoints: /health, /ready, /v1/tools, /v1/info."""
+
+from __future__ import annotations
+
+import time
+
+from fastapi import APIRouter, Request, Response
+
+from hudi_agent_gateway import __version__
+from hudi_agent_gateway.api.models import (
+ DependencyStatus,
+ InfoResponse,
+ ModelsResponse,
+ ReadyResponse,
+)
+from hudi_agent_gateway.llm import list_models
+
+router = APIRouter()
+
+
+@router.get("/health")
+async def health() -> dict[str, str]:
+ """Liveness: the process is up and serving."""
+ return {"status": "ok", "version": __version__}
+
+
+@router.get("/ready", response_model=ReadyResponse)
+async def ready(request: Request, response: Response) -> ReadyResponse:
+ """Readiness: configuration is valid AND dependencies are reachable."""
+ state = request.app.state
+ checks: dict[str, DependencyStatus] = {}
+
+ trino_ok = await state.trino_client.ping()
+ checks["trino"] = DependencyStatus(
+ ok=trino_ok,
+ detail="reachable" if trino_ok else
+ f"cannot reach trino at {state.settings.trino_host}:{state.settings.trino_port}",
+ )
+
+ llm_ok, llm_detail = await state.llm_readiness.check()
+ checks["llm"] = DependencyStatus(ok=llm_ok, detail=llm_detail)
+
+ all_ok = all(c.ok for c in checks.values())
+ if not all_ok:
+ response.status_code = 503
+ return ReadyResponse(ready=all_ok, checks=checks)
+
+
+@router.get("/v1/tools")
+async def list_tools(request: Request) -> dict[str, list[dict[str, object]]]:
+ return {"tools": request.app.state.registry.listing()}
+
+
+@router.get("/v1/models", response_model=ModelsResponse)
+async def models(request: Request) -> ModelsResponse:
+ """Models offered by the configured provider (live-discovered, 60s cache)."""
+ state = request.app.state
+ cache = getattr(state, "models_cache", None)
+ if cache is None or time.monotonic() - cache[0] > 60.0:
+ listed = await list_models(state.settings)
+ cache = (time.monotonic(), listed)
+ state.models_cache = cache
+ return ModelsResponse(
+ provider=state.settings.llm_provider,
+ default=state.settings.llm_model,
+ models=cache[1],
+ )
+
+
+@router.get("/v1/info", response_model=InfoResponse, response_model_by_alias=True)
+async def info(request: Request) -> InfoResponse:
+ s = request.app.state.settings
+ return InfoResponse(
+ name="hudi-agent-gateway",
+ version=__version__,
+ provider=s.llm_provider,
+ model=s.llm_model,
+ catalog=s.trino_catalog,
+ schema=s.trino_schema,
+ trino_url=f"http://{s.trino_host}:{s.trino_port}",
+ trino_ui_url=f"http://{s.trino_host}:{s.trino_port}/ui/",
+ mcp_enabled=s.mcp_enabled,
+ )
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/api/models.py b/hudi-agent-gateway/src/hudi_agent_gateway/api/models.py
new file mode 100644
index 000000000000..0c574e38829c
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/api/models.py
@@ -0,0 +1,112 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Request/response and SSE payload schemas for the HTTP API."""
+
+from __future__ import annotations
+
+from typing import Any, Literal
+
+from pydantic import BaseModel, Field
+
+
+class ChatRequest(BaseModel):
+ message: str = Field(min_length=1, description="The user's message.")
+ session_id: str = Field(
+ min_length=1,
+ max_length=128,
+ description="Conversation id; reuse it for multi-turn memory.",
+ )
+ stream: bool = Field(default=False, description="Stream the response as SSE.")
+ model: str | None = Field(
+ default=None,
+ max_length=200,
+ description="Model to use (within the configured provider); default when omitted.",
+ )
+
+
+class ToolTraceEntry(BaseModel):
+ name: str
+ args: dict[str, Any] = Field(default_factory=dict)
+ result_preview: str = ""
+ is_error: bool = False
+
+
+class ChatResponse(BaseModel):
+ session_id: str
+ message: str
+ tool_trace: list[ToolTraceEntry] = Field(default_factory=list)
+
+
+# --- SSE event payloads (each is the JSON body of one `data:` line) ---
+
+
+class TokenEvent(BaseModel):
+ text: str
+
+
+class ToolCallEvent(BaseModel):
+ id: str
+ name: str
+ args: dict[str, Any] = Field(default_factory=dict)
+
+
+class ToolResultEvent(BaseModel):
+ id: str
+ name: str
+ preview: str
+ is_error: bool = False
+
+
+class DoneEvent(BaseModel):
+ session_id: str
+ message: str
+
+
+class ErrorEvent(BaseModel):
+ code: Literal["llm_error", "agent_error", "recursion_limit"]
+ message: str
+
+
+class ModelsResponse(BaseModel):
+ provider: str
+ default: str
+ models: list[str]
+
+
+class DependencyStatus(BaseModel):
+ ok: bool
+ detail: str = ""
+
+
+class ReadyResponse(BaseModel):
+ ready: bool
+ checks: dict[str, DependencyStatus]
+
+
+class InfoResponse(BaseModel):
+ name: str
+ version: str
+ provider: str
+ model: str
+ catalog: str
+ schema_: str = Field(alias="schema")
+ # In-cluster/network endpoints, for the UI's connect panel.
+ trino_url: str
+ trino_ui_url: str
+ mcp_enabled: bool
+
+ model_config = {"populate_by_name": True}
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/app.py b/hudi-agent-gateway/src/hudi_agent_gateway/app.py
new file mode 100644
index 000000000000..de1faf8e8a6e
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/app.py
@@ -0,0 +1,97 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Application factory: one process, three surfaces (HTTP API, MCP, chat UI)."""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
+from importlib import resources
+
+from fastapi import FastAPI
+from fastapi.responses import RedirectResponse
+from fastapi.staticfiles import StaticFiles
+
+from hudi_agent_gateway import __version__
+from hudi_agent_gateway.agent import AgentCache
+from hudi_agent_gateway.api import chat, meta
+from hudi_agent_gateway.config import GatewaySettings
+from hudi_agent_gateway.llm import LLMReadiness
+from hudi_agent_gateway.log import log_event, setup_logging
+from hudi_agent_gateway.mcp_server import build_mcp
+from hudi_agent_gateway.sessions import SessionStore
+from hudi_agent_gateway.tools import build_registry
+from hudi_agent_gateway.tools.trino_client import TrinoClient
+
+logger = logging.getLogger("hudi_agent_gateway.app")
+
+
+def create_app(settings: GatewaySettings | None = None) -> FastAPI:
+ s = settings or GatewaySettings()
+ setup_logging(s.log_level)
+
+ trino_client = TrinoClient(s)
+ registry = build_registry(s, trino_client)
+ # NOTE: the MCP ASGI sub-app has its own lifespan that MUST run inside the
+ # outer app's lifespan, or FastMCP's streamable-HTTP session manager never
+ # starts and /mcp requests hang.
+ mcp_app = build_mcp(registry).http_app(path="/", stateless_http=True) if s.mcp_enabled else None
+
+ @asynccontextmanager
+ async def lifespan(app: FastAPI) -> AsyncIterator[None]:
+ app.state.settings = s
+ app.state.trino_client = trino_client
+ app.state.registry = registry
+ app.state.llm_readiness = LLMReadiness(s)
+ app.state.sessions = SessionStore(s)
+ app.state.agents = AgentCache(registry, app.state.sessions.checkpointer, s)
+ sweeper = asyncio.create_task(app.state.sessions.sweep_loop())
+ log_event(
+ logger,
+ "gateway_started",
+ version=__version__,
+ provider=s.llm_provider,
+ model=s.llm_model,
+ tools=len(registry),
+ mcp_enabled=s.mcp_enabled,
+ )
+ try:
+ if mcp_app is not None:
+ async with mcp_app.lifespan(app):
+ yield
+ else:
+ yield
+ finally:
+ sweeper.cancel()
+
+ app = FastAPI(title="hudi-agent-gateway", version=__version__, lifespan=lifespan)
+ app.include_router(meta.router)
+ app.include_router(chat.router)
+
+ if mcp_app is not None:
+ app.mount("/mcp", mcp_app)
+
+ ui_dir = resources.files("hudi_agent_gateway") / "ui"
+ app.mount("/ui", StaticFiles(directory=str(ui_dir), html=True), name="ui")
+
+ @app.get("/", include_in_schema=False)
+ async def root() -> RedirectResponse:
+ return RedirectResponse(url="/ui/")
+
+ return app
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/cli.py b/hudi-agent-gateway/src/hudi_agent_gateway/cli.py
new file mode 100644
index 000000000000..39044fe20ffe
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/cli.py
@@ -0,0 +1,52 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Command-line entrypoint: ``hudi-agent-gateway serve``."""
+
+from __future__ import annotations
+
+import argparse
+
+import uvicorn
+
+from hudi_agent_gateway import __version__
+
+
+def main(argv: list[str] | None = None) -> None:
+ parser = argparse.ArgumentParser(
+ prog="hudi-agent-gateway",
+ description="The Apache Hudi agent gateway server.",
+ )
+ parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
+ sub = parser.add_subparsers(dest="command", required=True)
+
+ serve = sub.add_parser("serve", help="Run the gateway server.")
+ serve.add_argument("--host", default=None, help="Bind address (overrides GATEWAY_HOST).")
+ serve.add_argument("--port", type=int, default=None, help="Bind port (overrides GATEWAY_PORT).")
+
+ args = parser.parse_args(argv)
+ if args.command == "serve":
+ # Import lazily so `--version`/`--help` never require full config.
+ from hudi_agent_gateway.config import GatewaySettings
+
+ settings = GatewaySettings()
+ uvicorn.run(
+ "hudi_agent_gateway.app:create_app",
+ factory=True,
+ host=args.host or settings.host,
+ port=args.port or settings.port,
+ log_config=None, # the gateway configures logging itself (JSON)
+ )
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/config.py b/hudi-agent-gateway/src/hudi_agent_gateway/config.py
new file mode 100644
index 000000000000..46f2d9836a08
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/config.py
@@ -0,0 +1,93 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Gateway configuration.
+
+Every knob is an environment variable prefixed ``GATEWAY_`` (except the
+provider API keys, which use their standard unprefixed names). Configuration
+errors fail fast at startup; connectivity problems do not -- they surface
+through ``/ready`` instead.
+"""
+
+from __future__ import annotations
+
+from typing import Literal
+
+from pydantic import AliasChoices, Field, model_validator
+from pydantic_settings import BaseSettings, SettingsConfigDict
+
+LLMProvider = Literal["anthropic", "openai", "ollama", "openai-compatible"]
+
+
+class GatewaySettings(BaseSettings):
+ model_config = SettingsConfigDict(
+ env_prefix="GATEWAY_", extra="ignore", populate_by_name=True
+ )
+
+ # --- server ---
+ host: str = "0.0.0.0"
+ port: int = 8000
+ log_level: str = "INFO"
+
+ # --- LLM ---
+ llm_provider: LLMProvider = "ollama"
+ llm_model: str = "qwen3:8b"
+ llm_timeout_seconds: float = 120.0
+ # Standard unprefixed key names, also accepted with the GATEWAY_ prefix.
+ anthropic_api_key: str = Field(
+ default="",
+ validation_alias=AliasChoices("ANTHROPIC_API_KEY", "GATEWAY_ANTHROPIC_API_KEY"),
+ )
+ openai_api_key: str = Field(
+ default="",
+ validation_alias=AliasChoices("OPENAI_API_KEY", "GATEWAY_OPENAI_API_KEY"),
+ )
+ ollama_base_url: str = "http://localhost:11434"
+ openai_base_url: str = "" # required for provider=openai-compatible (vLLM etc.)
+
+ # --- Trino / lakehouse ---
+ trino_host: str = "hudi-trino.hudi-lakehouse.svc"
+ trino_port: int = 8080
+ trino_user: str = "hudi-agent-gateway"
+ trino_catalog: str = "hudi"
+ trino_schema: str = "default"
+
+ # --- guardrails / shaping ---
+ sql_row_cap: int = 200
+ sql_timeout_seconds: float = 120.0
+ tool_result_max_bytes: int = 50_000
+
+ # --- agent / sessions ---
+ agent_max_iterations: int = 25
+ session_ttl_seconds: float = 3600.0
+ max_sessions: int = 1000
+ max_messages_per_session: int = 40
+ system_prompt_extra: str = ""
+
+ # --- surfaces ---
+ mcp_enabled: bool = True
+
+ @model_validator(mode="after")
+ def _validate_provider_requirements(self) -> GatewaySettings:
+ if self.llm_provider == "anthropic" and not self.anthropic_api_key:
+ raise ValueError("GATEWAY_LLM_PROVIDER=anthropic requires ANTHROPIC_API_KEY")
+ if self.llm_provider == "openai" and not self.openai_api_key:
+ raise ValueError("GATEWAY_LLM_PROVIDER=openai requires OPENAI_API_KEY")
+ if self.llm_provider == "openai-compatible" and not self.openai_base_url:
+ raise ValueError(
+ "GATEWAY_LLM_PROVIDER=openai-compatible requires GATEWAY_OPENAI_BASE_URL"
+ )
+ return self
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/llm.py b/hudi-agent-gateway/src/hudi_agent_gateway/llm.py
new file mode 100644
index 000000000000..ef5af575b9f2
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/llm.py
@@ -0,0 +1,177 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""LLM provider factory and provider-aware model discovery.
+
+Construction never touches the network, so the gateway always starts;
+connectivity is checked lazily and reported through ``/ready``. Model
+discovery (``list_models``) asks the configured provider what it offers, so
+the UI's model picker always reflects reality instead of a hardcoded list.
+"""
+
+from __future__ import annotations
+
+import logging
+import time
+
+import httpx
+from langchain_core.language_models.chat_models import BaseChatModel
+from pydantic import SecretStr
+
+from hudi_agent_gateway.config import GatewaySettings
+
+logger = logging.getLogger("hudi_agent_gateway.llm")
+
+
+def build_chat_model(settings: GatewaySettings, model: str | None = None) -> BaseChatModel:
+ provider = settings.llm_provider
+ model_name = model or settings.llm_model
+ if provider == "anthropic":
+ from langchain_anthropic import ChatAnthropic
+
+ return ChatAnthropic( # type: ignore[call-arg] # `model` is an init alias
+ model=model_name,
+ api_key=SecretStr(settings.anthropic_api_key),
+ timeout=settings.llm_timeout_seconds,
+ )
+ if provider == "openai":
+ from langchain_openai import ChatOpenAI
+
+ return ChatOpenAI(
+ model=model_name,
+ api_key=SecretStr(settings.openai_api_key),
+ timeout=settings.llm_timeout_seconds,
+ )
+ if provider == "ollama":
+ from langchain_ollama import ChatOllama
+
+ # ChatOllama has no `timeout` field; the timeout must reach the
+ # underlying httpx client, or a stalled Ollama hangs /v1/chat forever.
+ return ChatOllama(
+ model=model_name,
+ base_url=settings.ollama_base_url,
+ client_kwargs={"timeout": settings.llm_timeout_seconds},
+ )
+ if provider == "openai-compatible":
+ from langchain_openai import ChatOpenAI
+
+ return ChatOpenAI(
+ model=model_name,
+ base_url=settings.openai_base_url,
+ api_key=SecretStr(settings.openai_api_key or "unused"),
+ timeout=settings.llm_timeout_seconds,
+ )
+ raise ValueError(f"unsupported provider: {provider}") # unreachable; config validates
+
+
+async def list_models(settings: GatewaySettings, timeout: float = 5.0) -> list[str]:
+ """The models offered by the configured provider, default model first.
+
+ Falls back to just the configured default when the provider cannot be
+ listed -- the picker degrades to a single entry, chat keeps working.
+ """
+ try:
+ models = await _list_models_from_provider(settings, timeout)
+ except Exception as e: # noqa: BLE001 - discovery must never break the API
+ logger.warning("model listing failed for provider %s: %s", settings.llm_provider, e)
+ models = []
+ default = settings.llm_model
+ ordered = [default] + sorted(m for m in models if m != default)
+ return ordered
+
+
+async def _list_models_from_provider(settings: GatewaySettings, timeout: float) -> list[str]:
+ provider = settings.llm_provider
+ async with httpx.AsyncClient(timeout=timeout) as client:
+ if provider == "anthropic":
+ resp = await client.get(
+ "https://api.anthropic.com/v1/models",
+ headers={
+ "x-api-key": settings.anthropic_api_key,
+ "anthropic-version": "2023-06-01",
+ },
+ params={"limit": 100},
+ )
+ resp.raise_for_status()
+ return [m["id"] for m in resp.json().get("data", [])]
+ if provider == "openai":
+ resp = await client.get(
+ "https://api.openai.com/v1/models",
+ headers={"Authorization": f"Bearer {settings.openai_api_key}"},
+ )
+ resp.raise_for_status()
+ ids = [m["id"] for m in resp.json().get("data", [])]
+ # Keep chat-capable families; drop embeddings/audio/image models.
+ return [
+ i
+ for i in ids
+ if (i.startswith("gpt-") or i.startswith("o"))
+ and not any(x in i for x in ("embedding", "audio", "tts", "image", "dall-e"))
+ ]
+ if provider == "ollama":
+ resp = await client.get(settings.ollama_base_url.rstrip("/") + "/api/tags")
+ resp.raise_for_status()
+ return [m["name"] for m in resp.json().get("models", [])]
+ if provider == "openai-compatible":
+ headers = {}
+ if settings.openai_api_key:
+ headers["Authorization"] = f"Bearer {settings.openai_api_key}"
+ resp = await client.get(
+ settings.openai_base_url.rstrip("/") + "/models", headers=headers
+ )
+ resp.raise_for_status()
+ return [m["id"] for m in resp.json().get("data", [])]
+ return []
+
+
+class LLMReadiness:
+ """Cheap, cached reachability check feeding ``/ready``.
+
+ For local endpoints (ollama / openai-compatible) this probes the base URL;
+ for hosted providers a configured API key is treated as ready -- a live
+ call would cost money and rate limit.
+ """
+
+ def __init__(self, settings: GatewaySettings, cache_seconds: float = 10.0) -> None:
+ self._settings = settings
+ self._cache_seconds = cache_seconds
+ self._cached_at = 0.0
+ self._cached: tuple[bool, str] = (False, "not checked yet")
+
+ async def check(self) -> tuple[bool, str]:
+ now = time.monotonic()
+ if now - self._cached_at < self._cache_seconds:
+ return self._cached
+ self._cached = await self._probe()
+ self._cached_at = now
+ return self._cached
+
+ async def _probe(self) -> tuple[bool, str]:
+ s = self._settings
+ if s.llm_provider == "anthropic":
+ return True, "api key configured"
+ if s.llm_provider == "openai":
+ return True, "api key configured"
+ url = s.ollama_base_url if s.llm_provider == "ollama" else s.openai_base_url
+ probe = url.rstrip("/") + ("/api/tags" if s.llm_provider == "ollama" else "/models")
+ try:
+ async with httpx.AsyncClient(timeout=3.0) as client:
+ resp = await client.get(probe)
+ if resp.status_code < 500:
+ return True, f"reachable ({url})"
+ return False, f"endpoint returned {resp.status_code} ({url})"
+ except httpx.HTTPError as e:
+ return False, f"unreachable ({url}): {type(e).__name__}"
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/log.py b/hudi-agent-gateway/src/hudi_agent_gateway/log.py
new file mode 100644
index 000000000000..153470633634
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/log.py
@@ -0,0 +1,71 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Structured JSON logging.
+
+Every log record is one JSON object per line. Request/session correlation ids
+are carried in contextvars so tool invocations logged deep inside the agent
+loop still carry them. This is the seed of the gateway's trace collection.
+"""
+
+from __future__ import annotations
+
+import contextvars
+import json
+import logging
+import sys
+import time
+from typing import Any
+
+request_id_var: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="")
+session_id_var: contextvars.ContextVar[str] = contextvars.ContextVar("session_id", default="")
+
+
+class JsonFormatter(logging.Formatter):
+ def format(self, record: logging.LogRecord) -> str:
+ payload: dict[str, Any] = {
+ "ts": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime(record.created))
+ + f".{int(record.msecs):03d}Z",
+ "level": record.levelname,
+ "logger": record.name,
+ "message": record.getMessage(),
+ }
+ if request_id := request_id_var.get():
+ payload["request_id"] = request_id
+ if session_id := session_id_var.get():
+ payload["session_id"] = session_id
+ extra = getattr(record, "extra_fields", None)
+ if isinstance(extra, dict):
+ payload.update(extra)
+ if record.exc_info and record.exc_info[0] is not None:
+ payload["exception"] = self.formatException(record.exc_info)
+ return json.dumps(payload, default=str)
+
+
+def setup_logging(level: str = "INFO") -> None:
+ handler = logging.StreamHandler(sys.stdout)
+ handler.setFormatter(JsonFormatter())
+ root = logging.getLogger()
+ root.handlers = [handler]
+ root.setLevel(level.upper())
+ # Quiet chatty third-party loggers; the gateway's records carry the signal.
+ for noisy in ("uvicorn.access", "httpx", "httpcore"):
+ logging.getLogger(noisy).setLevel(logging.WARNING)
+
+
+def log_event(logger: logging.Logger, message: str, /, **fields: Any) -> None:
+ """Log a structured event, e.g. ``log_event(log, "tool_invocation", tool=...)``."""
+ logger.info(message, extra={"extra_fields": fields})
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/mcp_server.py b/hudi-agent-gateway/src/hudi_agent_gateway/mcp_server.py
new file mode 100644
index 000000000000..f1d17fd55365
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/mcp_server.py
@@ -0,0 +1,41 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""The MCP surface: the same tool registry, exposed to external agents."""
+
+from __future__ import annotations
+
+from fastmcp import FastMCP
+
+from hudi_agent_gateway import __version__
+from hudi_agent_gateway.tools.registry import ToolRegistry
+
+_INSTRUCTIONS = (
+ "Tools for querying an Apache Hudi lakehouse through Trino. Use list_tables "
+ "and describe_table to discover the schema, then query_lakehouse with a "
+ "single read-only SELECT statement (Trino SQL). Results are row-capped and "
+ "may be truncated (indicated in the payload)."
+)
+
+
+def build_mcp(registry: ToolRegistry) -> FastMCP:
+ mcp: FastMCP = FastMCP(
+ name="hudi-lakehouse",
+ version=__version__,
+ instructions=_INSTRUCTIONS,
+ )
+ registry.attach_to_mcp(mcp)
+ return mcp
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/py.typed b/hudi-agent-gateway/src/hudi_agent_gateway/py.typed
new file mode 100644
index 000000000000..c5a5d9fae9de
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/py.typed
@@ -0,0 +1,15 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/sessions.py b/hudi-agent-gateway/src/hudi_agent_gateway/sessions.py
new file mode 100644
index 000000000000..05cae8be64a1
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/sessions.py
@@ -0,0 +1,84 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Bounded in-memory session store.
+
+Sessions map to LangGraph checkpointer threads (``thread_id = session_id``).
+The store bounds memory growth two ways: an idle TTL and an LRU cap on the
+number of live sessions, both enforced by a background sweeper.
+
+Process-local by design => run a SINGLE replica. The seam for horizontal
+scale is swapping the checkpointer for ``langgraph-checkpoint-postgres``
+without touching callers.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import logging
+import time
+
+from langgraph.checkpoint.memory import InMemorySaver
+
+from hudi_agent_gateway.config import GatewaySettings
+from hudi_agent_gateway.log import log_event
+
+logger = logging.getLogger("hudi_agent_gateway.sessions")
+
+
+class SessionStore:
+ def __init__(self, settings: GatewaySettings) -> None:
+ self.checkpointer = InMemorySaver()
+ self._ttl = settings.session_ttl_seconds
+ self._max_sessions = settings.max_sessions
+ self._last_access: dict[str, float] = {}
+
+ def touch(self, session_id: str) -> None:
+ self._last_access[session_id] = time.monotonic()
+ self._evict_lru()
+
+ @property
+ def active_sessions(self) -> int:
+ return len(self._last_access)
+
+ def _delete(self, session_id: str, reason: str) -> None:
+ self._last_access.pop(session_id, None)
+ try:
+ self.checkpointer.delete_thread(session_id)
+ except Exception: # noqa: BLE001 - eviction must never take the server down
+ logger.warning("failed to delete thread %s", session_id, exc_info=True)
+ log_event(logger, "session_evicted", evicted_session_id=session_id, reason=reason)
+
+ def _evict_lru(self) -> None:
+ while len(self._last_access) > self._max_sessions:
+ oldest = min(self._last_access, key=self._last_access.__getitem__)
+ self._delete(oldest, "lru")
+
+ def sweep(self) -> int:
+ """Evict idle sessions; returns the number evicted."""
+ now = time.monotonic()
+ expired = [sid for sid, at in self._last_access.items() if now - at > self._ttl]
+ for sid in expired:
+ self._delete(sid, "ttl")
+ return len(expired)
+
+ async def sweep_loop(self, interval_seconds: float = 60.0) -> None:
+ while True:
+ await asyncio.sleep(interval_seconds)
+ try:
+ self.sweep()
+ except Exception: # noqa: BLE001
+ logger.warning("session sweep failed", exc_info=True)
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/tools/__init__.py b/hudi-agent-gateway/src/hudi_agent_gateway/tools/__init__.py
new file mode 100644
index 000000000000..9e4db82cdc7b
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/tools/__init__.py
@@ -0,0 +1,37 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Tool assembly: the single place where tool modules get registered.
+
+Adding a new tool module = write the module with a ``register(registry, ...)``
+function, then call it here.
+"""
+
+from __future__ import annotations
+
+from hudi_agent_gateway.config import GatewaySettings
+from hudi_agent_gateway.tools import trino_tools
+from hudi_agent_gateway.tools.registry import ToolRegistry
+from hudi_agent_gateway.tools.trino_client import TrinoClient
+
+
+def build_registry(
+ settings: GatewaySettings, trino_client: TrinoClient | None = None
+) -> ToolRegistry:
+ registry = ToolRegistry()
+ client = trino_client or TrinoClient(settings)
+ trino_tools.register(registry, client, settings)
+ return registry
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/tools/guardrails.py b/hudi-agent-gateway/src/hudi_agent_gateway/tools/guardrails.py
new file mode 100644
index 000000000000..ec261eada2ca
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/tools/guardrails.py
@@ -0,0 +1,92 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""SQL guardrails for model-written queries.
+
+AST-level (sqlglot, Trino dialect) rather than regex: read-only enforcement
+survives comments, CTEs, and string literals; the row cap is injected as a
+real ``LIMIT``. Fail-closed: anything that does not parse is rejected.
+"""
+
+from __future__ import annotations
+
+import sqlglot
+from sqlglot import exp
+
+from hudi_agent_gateway.tools.registry import ToolInputError
+
+_FORBIDDEN_NODES: tuple[type[exp.Expression], ...] = (
+ exp.Insert,
+ exp.Update,
+ exp.Delete,
+ exp.Merge,
+ exp.Create,
+ exp.Drop,
+ exp.Alter,
+ exp.TruncateTable,
+ exp.Grant,
+ exp.Set,
+ exp.Command, # also covers CALL and EXPLAIN, which parse as generic commands
+ exp.Use,
+)
+
+_HINT = "Provide exactly one read-only SELECT statement (Trino SQL)."
+
+
+def enforce_guardrails(sql: str, row_cap: int) -> str:
+ """Validate ``sql`` as a single read-only SELECT and cap its LIMIT.
+
+ Returns the (possibly rewritten) SQL to execute. Raises
+ :class:`ToolInputError` on any violation.
+ """
+ try:
+ statements = sqlglot.parse(sql, read="trino")
+ except sqlglot.errors.SqlglotError as e:
+ raise ToolInputError(f"could not parse SQL: {e}", hint=_HINT) from e
+
+ statements = [s for s in statements if s is not None]
+ if len(statements) != 1:
+ raise ToolInputError(
+ f"exactly one statement is allowed, got {len(statements)}", hint=_HINT
+ )
+ stmt = statements[0]
+
+ if not isinstance(stmt, (exp.Select, exp.SetOperation)):
+ raise ToolInputError(
+ f"read-only: only SELECT is allowed, got {type(stmt).__name__}", hint=_HINT
+ )
+
+ # Defense in depth: no write/DDL/command node anywhere in the tree
+ # (catches e.g. a CTE wrapping an INSERT).
+ for node in stmt.walk():
+ if isinstance(node, _FORBIDDEN_NODES):
+ raise ToolInputError(
+ f"read-only: {type(node).__name__} is not allowed", hint=_HINT
+ )
+
+ return _cap_limit(stmt, row_cap).sql(dialect="trino")
+
+
+def _cap_limit(stmt: exp.Query, row_cap: int) -> exp.Query:
+ limit = stmt.args.get("limit")
+ if limit is not None:
+ try:
+ existing = int(limit.expression.name)
+ except (TypeError, ValueError):
+ existing = None
+ if existing is not None and existing <= row_cap:
+ return stmt
+ return stmt.limit(row_cap)
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/tools/registry.py b/hudi-agent-gateway/src/hudi_agent_gateway/tools/registry.py
new file mode 100644
index 000000000000..92aa6106af92
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/tools/registry.py
@@ -0,0 +1,158 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""The tool registry: define a lakehouse tool ONCE, expose it everywhere.
+
+A tool is a typed async function whose parameters use
+``Annotated[..., Field(description=...)]``. From that single definition the
+registry derives:
+
+- LangChain ``StructuredTool``s for the in-process agent loop, and
+- FastMCP tool registrations for external MCP clients,
+
+and wraps every invocation with a structured JSON log record (name, duration,
+outcome) -- the same trace regardless of which surface called the tool.
+"""
+
+from __future__ import annotations
+
+import functools
+import inspect
+import json
+import logging
+import time
+from collections.abc import Awaitable, Callable
+from dataclasses import dataclass
+from typing import Any
+
+from langchain_core.tools import BaseTool, StructuredTool
+from pydantic import BaseModel
+
+from hudi_agent_gateway.log import log_event
+
+logger = logging.getLogger("hudi_agent_gateway.tools")
+
+ToolHandler = Callable[..., Awaitable[str]]
+
+
+class ToolInputError(Exception):
+ """Raised by guardrails/handlers for invalid tool input; carries a hint for the model."""
+
+ def __init__(self, message: str, hint: str = "") -> None:
+ super().__init__(message)
+ self.hint = hint
+
+
+@dataclass(frozen=True)
+class GatewayTool:
+ name: str
+ description: str
+ handler: ToolHandler
+
+
+def is_tool_error(content: str) -> bool:
+ """Whether a tool result string is an ``{"error": ...}`` payload.
+
+ Parses rather than substring-matches: a successful result whose data
+ merely mentions "error" (e.g. a column named ``error``) is not an error.
+ """
+ try:
+ parsed = json.loads(content)
+ except (json.JSONDecodeError, TypeError):
+ return False
+ return isinstance(parsed, dict) and "error" in parsed
+
+
+def _with_invocation_logging(name: str, fn: ToolHandler) -> ToolHandler:
+ @functools.wraps(fn)
+ async def wrapped(*args: Any, **kwargs: Any) -> str:
+ start = time.monotonic()
+ outcome = "ok"
+ try:
+ result = await fn(*args, **kwargs)
+ if is_tool_error(result):
+ outcome = "tool_error"
+ return result
+ except Exception:
+ outcome = "exception"
+ raise
+ finally:
+ log_event(
+ logger,
+ "tool_invocation",
+ tool=name,
+ args={k: v for k, v in kwargs.items()},
+ duration_ms=round((time.monotonic() - start) * 1000, 1),
+ outcome=outcome,
+ )
+
+ return wrapped
+
+
+class ToolRegistry:
+ """Order-preserving registry of :class:`GatewayTool`."""
+
+ def __init__(self) -> None:
+ self._tools: dict[str, GatewayTool] = {}
+
+ def register(self, name: str, description: str) -> Callable[[ToolHandler], ToolHandler]:
+ if name in self._tools:
+ raise ValueError(f"tool {name!r} is already registered")
+
+ def deco(fn: ToolHandler) -> ToolHandler:
+ wrapped = _with_invocation_logging(name, fn)
+ self._tools[name] = GatewayTool(name=name, description=description, handler=wrapped)
+ return fn
+
+ return deco
+
+ def get(self, name: str) -> GatewayTool:
+ return self._tools[name]
+
+ def __len__(self) -> int:
+ return len(self._tools)
+
+ def langchain_tools(self) -> list[BaseTool]:
+ return [
+ StructuredTool.from_function(
+ coroutine=tool.handler,
+ name=tool.name,
+ description=tool.description,
+ infer_schema=True,
+ )
+ for tool in self._tools.values()
+ ]
+
+ def attach_to_mcp(self, mcp: Any) -> None:
+ """Register every tool on a FastMCP server instance."""
+ for tool in self._tools.values():
+ mcp.tool(tool.handler, name=tool.name, description=tool.description)
+
+ def listing(self) -> list[dict[str, Any]]:
+ """Tool metadata for ``GET /v1/tools``: name, description, and JSON schema."""
+ out: list[dict[str, Any]] = []
+ for lc_tool in self.langchain_tools():
+ schema = lc_tool.tool_call_schema
+ out.append(
+ {
+ "name": lc_tool.name,
+ "description": lc_tool.description,
+ "input_schema": schema.model_json_schema()
+ if inspect.isclass(schema) and issubclass(schema, BaseModel)
+ else schema,
+ }
+ )
+ return out
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/tools/trino_client.py b/hudi-agent-gateway/src/hudi_agent_gateway/tools/trino_client.py
new file mode 100644
index 000000000000..2eda8730a454
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/tools/trino_client.py
@@ -0,0 +1,123 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Async wrapper over the (synchronous) Trino DB-API client."""
+
+from __future__ import annotations
+
+import asyncio
+import contextlib
+import time
+from concurrent.futures import ThreadPoolExecutor
+from dataclasses import dataclass, field
+from typing import Any
+
+import trino
+
+from hudi_agent_gateway.config import GatewaySettings
+
+
+class TrinoQueryError(Exception):
+ """A query failed on the Trino side; message is safe to surface to the model."""
+
+
+class TrinoTimeoutError(TrinoQueryError):
+ pass
+
+
+@dataclass
+class QueryResult:
+ columns: list[str]
+ rows: list[list[Any]]
+ row_count: int = field(init=False)
+
+ def __post_init__(self) -> None:
+ self.row_count = len(self.rows)
+
+
+class TrinoClient:
+ """Thin async facade: each query runs the sync client in a worker thread
+ under a hard timeout, and fetches at most ``max_rows`` from the cursor
+ regardless of what the SQL says (defense in depth behind the guardrails).
+ """
+
+ def __init__(self, settings: GatewaySettings) -> None:
+ self._settings = settings
+ # Dedicated bounded pool: a stuck query must not eat the loop's shared
+ # default executor, and the bound caps how many can pile up at all.
+ self._executor = ThreadPoolExecutor(max_workers=8, thread_name_prefix="trino-query")
+ self._ping_cache: tuple[float, bool] | None = None
+
+ def _connect(self) -> trino.dbapi.Connection:
+ s = self._settings
+ return trino.dbapi.connect(
+ host=s.trino_host,
+ port=s.trino_port,
+ user=s.trino_user,
+ catalog=s.trino_catalog,
+ schema=s.trino_schema,
+ http_scheme="http",
+ )
+
+ def _execute_sync(self, sql: str, max_rows: int, holder: dict[str, Any]) -> QueryResult:
+ with self._connect() as conn:
+ cursor = conn.cursor()
+ holder["cursor"] = cursor
+ try:
+ cursor.execute(sql)
+ rows = cursor.fetchmany(max_rows)
+ columns = [d[0] for d in cursor.description or []]
+ return QueryResult(columns=columns, rows=[list(r) for r in rows])
+ finally:
+ cursor.close()
+
+ async def execute(self, sql: str, *, timeout: float, max_rows: int) -> QueryResult:
+ # `holder` hands the cursor back across the thread boundary so the
+ # timeout path can cancel the query server-side; wait_for alone only
+ # abandons the await while the worker thread stays blocked in Trino.
+ holder: dict[str, Any] = {}
+ loop = asyncio.get_running_loop()
+ future = loop.run_in_executor(self._executor, self._execute_sync, sql, max_rows, holder)
+ try:
+ return await asyncio.wait_for(future, timeout=timeout)
+ except TimeoutError as e:
+ cursor = holder.get("cursor")
+ if cursor is not None:
+ # best-effort server-side cancel; the timeout error wins
+ with contextlib.suppress(Exception):
+ cursor.cancel()
+ raise TrinoTimeoutError(f"query exceeded the {timeout:.0f}s timeout") from e
+ except trino.exceptions.TrinoUserError as e:
+ raise TrinoQueryError(f"{e.error_name}: {e.message}") from e
+ except trino.exceptions.Error as e:
+ raise TrinoQueryError(str(e)) from e
+
+ async def ping(self, timeout: float = 5.0, cache_seconds: float = 10.0) -> bool:
+ """Cached reachability check feeding ``/ready``.
+
+ Cached like ``LLMReadiness`` so a 10s readinessProbe period does not
+ open a fresh connection and log a query in Trino on every probe.
+ """
+ now = time.monotonic()
+ if self._ping_cache is not None and now - self._ping_cache[0] < cache_seconds:
+ return self._ping_cache[1]
+ try:
+ await self.execute("SELECT 1", timeout=timeout, max_rows=1)
+ ok = True
+ except Exception:
+ ok = False
+ self._ping_cache = (now, ok)
+ return ok
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/tools/trino_tools.py b/hudi-agent-gateway/src/hudi_agent_gateway/tools/trino_tools.py
new file mode 100644
index 000000000000..95b6b33082d6
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/tools/trino_tools.py
@@ -0,0 +1,231 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Lakehouse tools backed by Trino.
+
+Handlers return JSON strings. Expected failures (guardrail rejections, query
+errors, timeouts) are returned as ``{"error": ..., "hint": ...}`` payloads
+rather than raised, so the agent can read the error and self-correct, and MCP
+clients get a useful result instead of a protocol error.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+from typing import Annotated, Any
+
+from pydantic import Field
+
+from hudi_agent_gateway.config import GatewaySettings
+from hudi_agent_gateway.tools.guardrails import enforce_guardrails
+from hudi_agent_gateway.tools.registry import ToolInputError, ToolRegistry
+from hudi_agent_gateway.tools.trino_client import (
+ QueryResult,
+ TrinoClient,
+ TrinoQueryError,
+ TrinoTimeoutError,
+)
+
+_QUERY_DESC = (
+ "Run a single read-only SELECT statement (Trino SQL) against the lakehouse "
+ "and return the result as JSON. A server-side row cap is enforced; results "
+ "may be truncated (indicated by `truncated: true`)."
+)
+_LIST_TABLES_DESC = (
+ "List tables in the lakehouse. Optionally filter by catalog and schema; "
+ "defaults to the gateway's configured catalog and schema."
+)
+_DESCRIBE_DESC = (
+ "Describe a table's columns and types. Accepts `table`, `schema.table`, or "
+ "`catalog.schema.table`."
+)
+
+
+def shape_result(result: QueryResult, *, max_bytes: int, sql: str, row_cap: int) -> str:
+ # A result that filled the row cap was almost certainly cut off by it
+ # (LIMIT rewrite + fetchmany), so report it truncated -- the agent warns
+ # the user instead of presenting a capped answer as complete.
+ row_capped = result.row_count >= row_cap
+ payload: dict[str, Any] = {
+ "sql": sql,
+ "columns": result.columns,
+ "rows": result.rows,
+ "row_count": result.row_count,
+ "truncated": row_capped,
+ }
+ if row_capped:
+ payload["notice"] = (
+ f"Result hit the {row_cap}-row cap and may be incomplete. "
+ "Narrow the query (filters, aggregation) for an exact answer."
+ )
+ text = json.dumps(payload, default=str)
+ while len(text.encode()) > max_bytes and payload["rows"]:
+ keep = max(1, len(payload["rows"]) // 2)
+ if keep == len(payload["rows"]):
+ keep -= 1
+ payload["rows"] = payload["rows"][:keep]
+ payload["truncated"] = True
+ payload["notice"] = (
+ f"Result truncated to {len(payload['rows'])} of {result.row_count} fetched rows "
+ "to fit the size limit. Narrow the query (filters, aggregation, fewer columns)."
+ )
+ text = json.dumps(payload, default=str)
+ if len(text.encode()) > max_bytes:
+ # Fail-safe: even zero rows can bust the limit (huge sql text, very
+ # many columns, or a tiny configured cap). Return a bounded payload.
+ text = json.dumps({
+ "sql": sql[:100],
+ "column_count": len(result.columns),
+ "rows": [],
+ "row_count": result.row_count,
+ "truncated": True,
+ "notice": "Result exceeded the size limit; rows and column names omitted. "
+ "Narrow the query or raise the result size limit.",
+ })
+ if len(text.encode()) > max_bytes:
+ text = json.dumps({"error": "result exceeded the size limit", "truncated": True})
+ return text
+
+
+def _error(message: str, hint: str = "") -> str:
+ payload = {"error": message}
+ if hint:
+ payload["hint"] = hint
+ return json.dumps(payload)
+
+
+_IDENTIFIER_RE = re.compile(r"^[A-Za-z_][A-Za-z0-9_$-]*$")
+
+
+def _validate_identifier(value: str, kind: str) -> str:
+ """Reject anything that could escape quoting when interpolated into SQL.
+
+ catalog/schema/table names arrive over HTTP and MCP; only plain
+ identifiers are accepted -- everything else is an input error.
+ """
+ if not _IDENTIFIER_RE.match(value):
+ raise ToolInputError(
+ f"invalid {kind} name {value!r}",
+ hint="Names may contain only letters, digits, '_', '$' or '-', "
+ "and must not start with a digit.",
+ )
+ return value
+
+
+def _split_table_name(table: str, settings: GatewaySettings) -> tuple[str, str, str]:
+ parts = table.split(".")
+ if len(parts) == 1:
+ return settings.trino_catalog, settings.trino_schema, parts[0]
+ if len(parts) == 2:
+ return settings.trino_catalog, parts[0], parts[1]
+ if len(parts) == 3:
+ return parts[0], parts[1], parts[2]
+ raise ToolInputError(
+ f"invalid table name {table!r}", hint="Use table, schema.table, or catalog.schema.table."
+ )
+
+
+def register(registry: ToolRegistry, client: TrinoClient, settings: GatewaySettings) -> None:
+ @registry.register("query_lakehouse", _QUERY_DESC)
+ async def query_lakehouse(
+ sql: Annotated[
+ str, Field(description="A single read-only SELECT statement in Trino SQL.")
+ ],
+ ) -> str:
+ try:
+ safe_sql = enforce_guardrails(sql, row_cap=settings.sql_row_cap)
+ result = await client.execute(
+ safe_sql, timeout=settings.sql_timeout_seconds, max_rows=settings.sql_row_cap
+ )
+ except ToolInputError as e:
+ return _error(str(e), e.hint)
+ except TrinoTimeoutError as e:
+ return _error(
+ f"query failed: {e}",
+ f"The query hit the gateway's {settings.sql_timeout_seconds:.0f}s limit -- "
+ "narrow it (partition filter, pre-aggregate, fewer columns) or raise "
+ "GATEWAY_SQL_TIMEOUT_SECONDS.",
+ )
+ except TrinoQueryError as e:
+ return _error(f"query failed: {e}", "Fix the SQL and try again.")
+ return shape_result(
+ result,
+ max_bytes=settings.tool_result_max_bytes,
+ sql=safe_sql,
+ row_cap=settings.sql_row_cap,
+ )
+
+ @registry.register("list_tables", _LIST_TABLES_DESC)
+ async def list_tables(
+ catalog: Annotated[
+ str, Field(description="Catalog to list from; empty for the default.")
+ ] = "",
+ schema_name: Annotated[
+ str, Field(description="Schema to list from; empty for the default.")
+ ] = "",
+ ) -> str:
+ try:
+ cat = _validate_identifier(catalog or settings.trino_catalog, "catalog")
+ sch = _validate_identifier(schema_name or settings.trino_schema, "schema")
+ except ToolInputError as e:
+ return _error(str(e), e.hint)
+ sql = (
+ f'SELECT table_schema, table_name, table_type FROM "{cat}".information_schema.tables '
+ f"WHERE table_schema = '{sch}' ORDER BY table_name"
+ )
+ try:
+ result = await client.execute(
+ sql, timeout=settings.sql_timeout_seconds, max_rows=settings.sql_row_cap
+ )
+ except TrinoQueryError as e:
+ return _error(f"listing tables failed: {e}")
+ return shape_result(
+ result, max_bytes=settings.tool_result_max_bytes, sql=sql, row_cap=settings.sql_row_cap
+ )
+
+ @registry.register("describe_table", _DESCRIBE_DESC)
+ async def describe_table(
+ table: Annotated[
+ str, Field(description="Table name: table, schema.table, or catalog.schema.table.")
+ ],
+ ) -> str:
+ try:
+ cat, sch, tbl = _split_table_name(table, settings)
+ _validate_identifier(cat, "catalog")
+ _validate_identifier(sch, "schema")
+ _validate_identifier(tbl, "table")
+ except ToolInputError as e:
+ return _error(str(e), e.hint)
+ sql = (
+ "SELECT column_name, data_type, is_nullable "
+ f'FROM "{cat}".information_schema.columns '
+ f"WHERE table_schema = '{sch}' AND table_name = '{tbl}' ORDER BY ordinal_position"
+ )
+ try:
+ result = await client.execute(
+ sql, timeout=settings.sql_timeout_seconds, max_rows=settings.sql_row_cap
+ )
+ except TrinoQueryError as e:
+ return _error(f"describe failed: {e}")
+ if result.row_count == 0:
+ return _error(
+ f"table {cat}.{sch}.{tbl} not found",
+ "Call list_tables to see available tables.",
+ )
+ return shape_result(
+ result, max_bytes=settings.tool_result_max_bytes, sql=sql, row_cap=settings.sql_row_cap
+ )
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/ui/app.js b/hudi-agent-gateway/src/hudi_agent_gateway/ui/app.js
new file mode 100644
index 000000000000..8fa4186eccf4
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/ui/app.js
@@ -0,0 +1,268 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Chat client for the hudi-agent-gateway. Talks to POST /v1/chat with
+ * stream=true and renders the SSE event stream: token / tool_call /
+ * tool_result / done / error. First-party code only.
+ */
+(function () {
+ "use strict";
+
+ var messagesEl = document.getElementById("messages");
+ var welcomeEl = document.getElementById("welcome");
+ var inputEl = document.getElementById("input");
+ var sendEl = document.getElementById("send");
+ var composerEl = document.getElementById("composer");
+ var modelInfoEl = document.getElementById("model-info");
+
+ var modelSelectEl = document.getElementById("model-select");
+
+ var SESSION_KEY = "hudi-agent-gateway.session";
+ var MODEL_KEY = "hudi-agent-gateway.model";
+ var sessionId = localStorage.getItem(SESSION_KEY) || newSession();
+ var selectedModel = null;
+ var busy = false;
+
+ function newSession() {
+ var id = (crypto.randomUUID && crypto.randomUUID()) ||
+ "s-" + Date.now() + "-" + Math.floor(Math.random() * 1e9);
+ localStorage.setItem(SESSION_KEY, id);
+ return id;
+ }
+
+ fetch("../v1/info").then(function (r) { return r.json(); }).then(function (info) {
+ modelInfoEl.textContent = info.provider + " · catalog " + info.catalog;
+ var base = window.location.origin;
+ document.getElementById("ep-trino").textContent = info.trino_url;
+ var trinoUi = document.getElementById("ep-trino-ui");
+ trinoUi.textContent = info.trino_ui_url;
+ trinoUi.href = info.trino_ui_url;
+ document.getElementById("ep-chat").textContent = base + "/v1/chat";
+ document.getElementById("ep-mcp").textContent = base + "/mcp/";
+ document.getElementById("ep-mcp-hint").textContent =
+ "for agents: claude mcp add --transport http hudi-lakehouse " + base + "/mcp/";
+ if (!info.mcp_enabled) document.getElementById("ep-mcp-row").hidden = true;
+ }).catch(function () { modelInfoEl.textContent = "gateway unreachable"; });
+
+ var connectToggle = document.getElementById("connect-toggle");
+ var connectPanel = document.getElementById("connect-panel");
+ connectToggle.addEventListener("click", function () {
+ connectPanel.hidden = !connectPanel.hidden;
+ connectToggle.classList.toggle("open", !connectPanel.hidden);
+ });
+ document.querySelectorAll(".copy").forEach(function (btn) {
+ btn.addEventListener("click", function () {
+ var text = document.getElementById(btn.dataset.copy).textContent;
+ navigator.clipboard.writeText(text).then(function () {
+ btn.textContent = "✓";
+ setTimeout(function () { btn.textContent = "⎘"; }, 1200);
+ });
+ });
+ });
+
+ // Populate the model picker with whatever the configured provider offers.
+ fetch("../v1/models").then(function (r) { return r.json(); }).then(function (m) {
+ var remembered = localStorage.getItem(MODEL_KEY);
+ selectedModel = (remembered && m.models.indexOf(remembered) !== -1)
+ ? remembered : m.default;
+ m.models.forEach(function (name) {
+ var opt = document.createElement("option");
+ opt.value = name;
+ opt.textContent = name;
+ if (name === selectedModel) opt.selected = true;
+ modelSelectEl.appendChild(opt);
+ });
+ modelSelectEl.hidden = false;
+ if (m.models.length <= 1) modelSelectEl.disabled = true; // e.g. vLLM: one model
+ modelSelectEl.addEventListener("change", function () {
+ selectedModel = modelSelectEl.value;
+ localStorage.setItem(MODEL_KEY, selectedModel);
+ });
+ }).catch(function () { /* picker simply stays hidden */ });
+
+ document.getElementById("clear-chat").addEventListener("click", function () {
+ sessionId = newSession();
+ messagesEl.querySelectorAll(".msg, .error-banner").forEach(function (el) { el.remove(); });
+ if (welcomeEl) welcomeEl.style.display = "";
+ inputEl.focus();
+ });
+
+ messagesEl.addEventListener("click", function (e) {
+ if (e.target.classList.contains("suggestion")) {
+ inputEl.value = e.target.textContent;
+ composerEl.requestSubmit();
+ }
+ });
+
+ inputEl.addEventListener("keydown", function (e) {
+ if (e.key === "Enter" && !e.shiftKey) {
+ e.preventDefault();
+ composerEl.requestSubmit();
+ }
+ });
+ inputEl.addEventListener("input", function () {
+ inputEl.style.height = "auto";
+ inputEl.style.height = Math.min(inputEl.scrollHeight, 160) + "px";
+ });
+
+ composerEl.addEventListener("submit", function (e) {
+ e.preventDefault();
+ var text = inputEl.value.trim();
+ if (!text || busy) return;
+ inputEl.value = "";
+ inputEl.style.height = "auto";
+ send(text);
+ });
+
+ function el(tag, className, parent) {
+ var node = document.createElement(tag);
+ if (className) node.className = className;
+ if (parent) parent.appendChild(node);
+ return node;
+ }
+
+ function scrollToBottom() {
+ messagesEl.scrollTop = messagesEl.scrollHeight;
+ }
+
+ function addUserMessage(text) {
+ if (welcomeEl) welcomeEl.style.display = "none";
+ var msg = el("div", "msg user", messagesEl);
+ var bubble = el("div", "bubble", msg);
+ bubble.textContent = text;
+ scrollToBottom();
+ }
+
+ function addErrorBanner(text) {
+ var banner = el("div", "error-banner", messagesEl);
+ banner.textContent = text;
+ scrollToBottom();
+ }
+
+ function setBusy(value) {
+ busy = value;
+ sendEl.disabled = value;
+ }
+
+ function send(text) {
+ addUserMessage(text);
+ setBusy(true);
+
+ var msg = el("div", "msg assistant", messagesEl);
+ var bubble = el("div", "bubble md", msg);
+ var answer = "";
+ var cursor = el("span", "cursor", bubble);
+ var chips = {};
+
+ function renderAnswer() {
+ bubble.innerHTML = window.HudiMarkdown.render(answer);
+ if (busy) bubble.appendChild(cursor);
+ scrollToBottom();
+ }
+
+ var payload = { message: text, session_id: sessionId, stream: true };
+ if (selectedModel) payload.model = selectedModel;
+ fetch("../v1/chat", {
+ method: "POST",
+ headers: { "Content-Type": "application/json", "Accept": "text/event-stream" },
+ body: JSON.stringify(payload)
+ }).then(function (resp) {
+ if (!resp.ok || !resp.body) {
+ return resp.text().then(function (body) {
+ throw new Error("gateway returned " + resp.status + ": " + body.slice(0, 300));
+ });
+ }
+ var reader = resp.body.getReader();
+ var decoder = new TextDecoder();
+ var buffer = "";
+
+ function pump() {
+ return reader.read().then(function (step) {
+ if (step.done) { finish(); return null; }
+ // Normalize SSE line endings (servers may emit \r\n) before framing.
+ buffer += decoder.decode(step.value, { stream: true }).replace(/\r/g, "");
+ var frames = buffer.split("\n\n");
+ buffer = frames.pop();
+ frames.forEach(handleFrame);
+ return pump();
+ });
+ }
+ return pump();
+ }).catch(function (err) {
+ addErrorBanner(err.message || String(err));
+ finish();
+ });
+
+ function handleFrame(frame) {
+ var event = "message";
+ var dataLines = [];
+ frame.split("\n").forEach(function (line) {
+ if (line.startsWith("event:")) event = line.slice(6).trim();
+ else if (line.startsWith("data:")) dataLines.push(line.slice(5).trim());
+ });
+ if (!dataLines.length) return;
+ var data;
+ try { data = JSON.parse(dataLines.join("\n")); } catch (e) { return; }
+
+ if (event === "token") {
+ answer += data.text;
+ renderAnswer();
+ } else if (event === "tool_call") {
+ var chip = el("details", "tool-chip running", bubble.parentNode);
+ bubble.parentNode.insertBefore(chip, bubble);
+ var summary = el("summary", "", chip);
+ summary.textContent = data.name;
+ var pre = el("pre", "", chip);
+ pre.textContent = JSON.stringify(data.args, null, 2);
+ chips[data.id || data.name] = chip;
+ scrollToBottom();
+ } else if (event === "tool_result") {
+ var target = chips[data.id || data.name];
+ if (target) {
+ target.classList.remove("running");
+ if (data.is_error) target.classList.add("error");
+ var summaryEl = target.querySelector("summary");
+ summaryEl.textContent = data.name + (data.is_error ? " — error" : " ✓");
+ var result = el("pre", "", target);
+ result.textContent = data.preview;
+ }
+ scrollToBottom();
+ } else if (event === "error") {
+ addErrorBanner(data.code + ": " + data.message);
+ } else if (event === "done") {
+ if (!answer && data.message) {
+ answer = data.message;
+ renderAnswer();
+ }
+ }
+ }
+
+ function finish() {
+ setBusy(false);
+ if (cursor.parentNode) cursor.remove();
+ if (!answer && !msg.querySelector(".tool-chip")) {
+ bubble.innerHTML = "<p><em>(no response)</em></p>";
+ } else {
+ bubble.innerHTML = window.HudiMarkdown.render(answer);
+ }
+ scrollToBottom();
+ inputEl.focus();
+ }
+ }
+})();
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/ui/index.html b/hudi-agent-gateway/src/hudi_agent_gateway/ui/index.html
new file mode 100644
index 000000000000..d924ce4d047f
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/ui/index.html
@@ -0,0 +1,105 @@
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+<!doctype html>
+<html lang="en">
+<head>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1" />
+ <title>Hudi Agent Gateway</title>
+ <link rel="stylesheet" href="style.css" />
+</head>
+<body>
+ <header>
+ <div class="brand">
+ <img class="logo" src="https://hudi.apache.org/assets/images/hudi-logo-medium.png" alt="Apache Hudi" />
+ <span>
+ <strong>Agent Gateway</strong>
+ <small id="model-info">connecting…</small>
+ </span>
+ <select id="model-select" title="Model (within the configured provider)" hidden></select>
+ </div>
+ <div class="header-actions">
+ <button id="connect-toggle" title="Endpoints for SQL tools, apps, and agents">Connect</button>
+ <button id="clear-chat" title="Clear the conversation (history is not persisted)">Clear chat</button>
+ </div>
+ </header>
+
+ <section id="connect-panel" hidden>
+ <div class="endpoint">
+ <div>
+ <strong>Trino SQL</strong>
+ <small>point any SQL client / BI tool at the lakehouse directly</small>
+ </div>
+ <code id="ep-trino">…</code>
+ <button class="copy" data-copy="ep-trino" title="Copy">⎘</button>
+ </div>
+ <div class="endpoint">
+ <div>
+ <strong>Trino Web UI</strong>
+ <small>query monitoring & cluster overview</small>
+ </div>
+ <code><a id="ep-trino-ui" href="#" target="_blank" rel="noopener">…</a></code>
+ <button class="copy" data-copy="ep-trino-ui" title="Copy">⎘</button>
+ </div>
+ <div class="endpoint">
+ <div>
+ <strong>Inference API</strong>
+ <small>POST {"message", "session_id"} — the agent loop over your data</small>
+ </div>
+ <code id="ep-chat">…</code>
+ <button class="copy" data-copy="ep-chat" title="Copy">⎘</button>
+ </div>
+ <div class="endpoint" id="ep-mcp-row">
+ <div>
+ <strong>MCP server</strong>
+ <small id="ep-mcp-hint">for agents: claude mcp add --transport http hudi-lakehouse <url></small>
+ </div>
+ <code id="ep-mcp">…</code>
+ <button class="copy" data-copy="ep-mcp" title="Copy">⎘</button>
+ </div>
+ <p class="endpoint-note">Trino is addressed by its in-cluster service name; from outside the
+ cluster, port-forward or expose the service. The inference and MCP URLs are this gateway.</p>
+ </section>
+
+ <main id="messages" aria-live="polite">
+ <div class="welcome" id="welcome">
+ <h1>Talk to your lakehouse</h1>
+ <p>Ask questions about your Hudi tables in plain English. The agent
+ inspects the catalog, writes guarded Trino SQL, and answers from real
+ query results.</p>
+ <div class="suggestions">
+ <button class="suggestion">What tables are available?</button>
+ <button class="suggestion">Pick a table and summarize what it contains</button>
+ <button class="suggestion">Find interesting patterns in one of the tables</button>
+ </div>
+ </div>
+ </main>
+
+ <footer>
+ <form id="composer">
+ <textarea id="input" rows="1" placeholder="Ask about your data…"
+ autocomplete="off" autofocus></textarea>
+ <button id="send" type="submit" title="Send">➤</button>
+ </form>
+ <p class="fineprint">Answers are generated from live queries against your lakehouse. Verify before acting.</p>
+ </footer>
+
+ <script src="markdown.js"></script>
+ <script src="app.js"></script>
+</body>
+</html>
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/ui/markdown.js b/hudi-agent-gateway/src/hudi_agent_gateway/ui/markdown.js
new file mode 100644
index 000000000000..6ff8bdbe442d
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/ui/markdown.js
@@ -0,0 +1,130 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+/**
+ * Minimal first-party markdown renderer for the subset the gateway's agent
+ * emits: paragraphs, bold/italic, inline + fenced code, links, lists, and
+ * tables. All input is HTML-escaped before any markup is applied, so the
+ * output is XSS-safe by construction. No third-party code.
+ */
+(function () {
+ "use strict";
+
+ function escapeHtml(s) {
+ return s
+ .replace(/&/g, "&")
+ .replace(/</g, "<")
+ .replace(/>/g, ">")
+ .replace(/"/g, """);
+ }
+
+ function inline(s) {
+ return s
+ .replace(/`([^`]+)`/g, function (_, code) { return "<code>" + code + "</code>"; })
+ .replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
+ .replace(/(^|[^*])\*([^*\s][^*]*)\*/g, "$1<em>$2</em>")
+ .replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g,
+ '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
+ }
+
+ function isTableDivider(line) {
+ return /^\s*\|?[\s:|-]+\|[\s:|-]*$/.test(line) && line.indexOf("-") !== -1;
+ }
+
+ function splitRow(line) {
+ var t = line.trim();
+ if (t.startsWith("|")) t = t.slice(1);
+ if (t.endsWith("|")) t = t.slice(0, -1);
+ return t.split("|").map(function (c) { return c.trim(); });
+ }
+
+ function render(md) {
+ var lines = escapeHtml(md).split("\n");
+ var html = [];
+ var i = 0;
+
+ while (i < lines.length) {
+ var line = lines[i];
+
+ if (/^\s*```/.test(line)) { // fenced code block
+ var code = [];
+ i++;
+ while (i < lines.length && !/^\s*```/.test(lines[i])) { code.push(lines[i]); i++; }
+ i++; // closing fence
+ html.push("<pre><code>" + code.join("\n") + "</code></pre>");
+ continue;
+ }
+
+ if (line.indexOf("|") !== -1 && i + 1 < lines.length && isTableDivider(lines[i + 1])) {
+ var head = splitRow(line);
+ i += 2;
+ var body = [];
+ while (i < lines.length && lines[i].indexOf("|") !== -1 && lines[i].trim() !== "") {
+ body.push(splitRow(lines[i])); i++;
+ }
+ var t = "<table><thead><tr>";
+ head.forEach(function (h) { t += "<th>" + inline(h) + "</th>"; });
+ t += "</tr></thead><tbody>";
+ body.forEach(function (row) {
+ t += "<tr>";
+ row.forEach(function (c) { t += "<td>" + inline(c) + "</td>"; });
+ t += "</tr>";
+ });
+ t += "</tbody></table>";
+ html.push(t);
+ continue;
+ }
+
+ if (/^\s*(?:[-*]|\d+\.)\s+/.test(line)) { // list block
+ var ordered = /^\s*\d+\./.test(line);
+ var items = [];
+ while (i < lines.length && /^\s*(?:[-*]|\d+\.)\s+/.test(lines[i])) {
+ items.push(lines[i].replace(/^\s*(?:[-*]|\d+\.)\s+/, "")); i++;
+ }
+ var tag = ordered ? "ol" : "ul";
+ html.push("<" + tag + ">" + items.map(function (it) {
+ return "<li>" + inline(it) + "</li>";
+ }).join("") + "</" + tag + ">");
+ continue;
+ }
+
+ var h = line.match(/^(#{1,4})\s+(.*)$/); // headings
+ if (h) {
+ var level = Math.min(h[1].length + 2, 6); // demote: chat bubbles, not documents
+ html.push("<h" + level + ">" + inline(h[2]) + "</h" + level + ">");
+ i++;
+ continue;
+ }
+
+ if (line.trim() === "") { i++; continue; }
+
+ var para = [line]; // paragraph (merge soft-wrapped lines)
+ i++;
+ while (i < lines.length && lines[i].trim() !== "" &&
+ !/^\s*(?:```|[-*]\s|\d+\.\s|#)/.test(lines[i]) &&
+ !(lines[i].indexOf("|") !== -1 && i + 1 < lines.length && isTableDivider(lines[i + 1]))) {
+ para.push(lines[i]); i++;
+ }
+ html.push("<p>" + inline(para.join(" ")) + "</p>");
+ }
+
+ return html.join("\n");
+ }
+
+ window.HudiMarkdown = { render: render, escapeHtml: escapeHtml };
+})();
diff --git a/hudi-agent-gateway/src/hudi_agent_gateway/ui/style.css b/hudi-agent-gateway/src/hudi_agent_gateway/ui/style.css
new file mode 100644
index 000000000000..b4c0e5e129a3
--- /dev/null
+++ b/hudi-agent-gateway/src/hudi_agent_gateway/ui/style.css
@@ -0,0 +1,260 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+:root {
+ --bg: #f7f7f8;
+ --panel: #ffffff;
+ --text: #1a1a1e;
+ --muted: #6b6b76;
+ --border: #e3e3e8;
+ --accent: #2563eb;
+ --accent-soft: #eff4ff;
+ --user-bubble: #2563eb;
+ --user-text: #ffffff;
+ --chip-bg: #f1f5f9;
+ --code-bg: #f4f4f5;
+ --error: #b91c1c;
+ --error-bg: #fee2e2;
+}
+@media (prefers-color-scheme: dark) {
+ :root {
+ --bg: #131316;
+ --panel: #1d1d22;
+ --text: #ececf1;
+ --muted: #9d9da8;
+ --border: #2e2e36;
+ --accent: #60a5fa;
+ --accent-soft: #1d2839;
+ --user-bubble: #2b4c86;
+ --user-text: #ececf1;
+ --chip-bg: #26262e;
+ --code-bg: #101014;
+ --error: #fca5a5;
+ --error-bg: #3f1d1d;
+ }
+}
+
+* { box-sizing: border-box; }
+html, body { height: 100%; margin: 0; }
+body {
+ display: flex;
+ flex-direction: column;
+ background: var(--bg);
+ color: var(--text);
+ font: 15px/1.55 -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
+}
+
+header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 10px 18px;
+ background: var(--panel);
+ border-bottom: 1px solid var(--border);
+}
+.brand { display: flex; align-items: center; gap: 10px; }
+.brand .logo { height: 30px; width: auto; display: block; }
+@media (prefers-color-scheme: dark) {
+ /* Keep the wordmark legible on dark backgrounds. */
+ .brand .logo { background: #f7f7f8; border-radius: 6px; padding: 3px 7px; }
+}
+.brand strong { display: block; font-size: 15px; }
+.brand small { display: block; color: var(--muted); font-size: 12px; }
+#model-select {
+ margin-left: 10px;
+ border: 1px solid var(--border);
+ background: var(--bg);
+ color: var(--text);
+ border-radius: 8px;
+ padding: 5px 8px;
+ font: inherit;
+ font-size: 13px;
+ max-width: 260px;
+}
+.header-actions { display: flex; gap: 8px; }
+#clear-chat, #connect-toggle {
+ border: 1px solid var(--border);
+ background: transparent;
+ color: var(--text);
+ border-radius: 8px;
+ padding: 6px 12px;
+ cursor: pointer;
+}
+#clear-chat:hover, #connect-toggle:hover { background: var(--accent-soft); }
+#connect-toggle.open { background: var(--accent-soft); border-color: var(--accent); }
+
+#connect-panel {
+ background: var(--panel);
+ border-bottom: 1px solid var(--border);
+ padding: 12px 18px;
+}
+.endpoint {
+ display: flex;
+ align-items: center;
+ gap: 14px;
+ max-width: 900px;
+ margin: 0 auto 8px;
+}
+.endpoint > div { width: 220px; flex-shrink: 0; }
+.endpoint strong { display: block; font-size: 13.5px; }
+.endpoint small { color: var(--muted); font-size: 11.5px; }
+.endpoint code {
+ flex: 1;
+ background: var(--code-bg);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 7px 10px;
+ font-size: 12.5px;
+ overflow-x: auto;
+ white-space: nowrap;
+}
+.endpoint .copy {
+ border: 1px solid var(--border);
+ background: transparent;
+ color: var(--muted);
+ border-radius: 6px;
+ padding: 5px 9px;
+ cursor: pointer;
+ font-size: 14px;
+}
+.endpoint .copy:hover { color: var(--accent); border-color: var(--accent); }
+.endpoint-note {
+ max-width: 900px;
+ margin: 4px auto 0;
+ color: var(--muted);
+ font-size: 11.5px;
+}
+
+main {
+ flex: 1;
+ overflow-y: auto;
+ padding: 24px 0 12px;
+}
+.welcome { max-width: 680px; margin: 8vh auto 0; text-align: center; padding: 0 20px; }
+.welcome h1 { font-size: 26px; margin-bottom: 8px; }
+.welcome p { color: var(--muted); }
+.suggestions { display: flex; flex-wrap: wrap; gap: 8px; justify-content: center; margin-top: 18px; }
+.suggestion {
+ border: 1px solid var(--border);
+ background: var(--panel);
+ color: var(--text);
+ border-radius: 999px;
+ padding: 8px 14px;
+ cursor: pointer;
+ font-size: 13px;
+}
+.suggestion:hover { border-color: var(--accent); color: var(--accent); }
+
+.msg { max-width: 760px; margin: 0 auto 18px; padding: 0 20px; display: flex; }
+.msg.user { justify-content: flex-end; }
+.msg .bubble {
+ border-radius: 14px;
+ padding: 10px 14px;
+ max-width: 85%;
+ overflow-wrap: break-word;
+}
+.msg.user .bubble { background: var(--user-bubble); color: var(--user-text); }
+.msg.assistant { display: block; }
+.msg.assistant .bubble { background: transparent; padding: 0; max-width: 100%; }
+
+.tool-chip {
+ display: block;
+ margin: 6px 0;
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ background: var(--chip-bg);
+ font-size: 12.5px;
+ overflow: hidden;
+}
+.tool-chip > summary {
+ cursor: pointer;
+ padding: 7px 12px;
+ color: var(--muted);
+ list-style: none;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ user-select: none;
+}
+.tool-chip > summary::before { content: "\2699"; }
+.tool-chip.running > summary::before { content: ""; width: 10px; height: 10px; border: 2px solid var(--accent); border-top-color: transparent; border-radius: 50%; animation: spin 0.9s linear infinite; }
+.tool-chip.error > summary { color: var(--error); }
+.tool-chip pre {
+ margin: 0;
+ padding: 10px 12px;
+ border-top: 1px solid var(--border);
+ background: var(--code-bg);
+ overflow-x: auto;
+ font-size: 12px;
+}
+@keyframes spin { to { transform: rotate(360deg); } }
+
+.md p { margin: 0.4em 0; }
+.md table { border-collapse: collapse; margin: 8px 0; font-size: 13.5px; }
+.md th, .md td { border: 1px solid var(--border); padding: 5px 10px; text-align: left; }
+.md th { background: var(--chip-bg); }
+.md code { background: var(--code-bg); border-radius: 4px; padding: 1px 5px; font-size: 13px; }
+.md pre { background: var(--code-bg); border-radius: 8px; padding: 10px 12px; overflow-x: auto; }
+.md pre code { background: transparent; padding: 0; }
+.md ul, .md ol { margin: 0.4em 0; padding-left: 1.4em; }
+
+.cursor { display: inline-block; width: 8px; height: 1em; background: var(--accent); vertical-align: text-bottom; animation: blink 1s steps(2) infinite; }
+@keyframes blink { 50% { opacity: 0; } }
+
+.error-banner {
+ max-width: 760px;
+ margin: 0 auto 18px;
+ padding: 10px 14px;
+ border-radius: 10px;
+ background: var(--error-bg);
+ color: var(--error);
+ font-size: 13.5px;
+}
+
+footer { background: var(--panel); border-top: 1px solid var(--border); padding: 12px 18px 8px; }
+#composer {
+ display: flex;
+ gap: 10px;
+ max-width: 760px;
+ margin: 0 auto;
+ align-items: flex-end;
+}
+#input {
+ flex: 1;
+ resize: none;
+ border: 1px solid var(--border);
+ border-radius: 12px;
+ background: var(--bg);
+ color: var(--text);
+ padding: 10px 14px;
+ font: inherit;
+ max-height: 160px;
+}
+#input:focus { outline: 2px solid var(--accent); border-color: transparent; }
+#send {
+ border: none;
+ background: var(--accent);
+ color: #fff;
+ width: 40px;
+ height: 40px;
+ border-radius: 10px;
+ font-size: 16px;
+ cursor: pointer;
+}
+#send:disabled { opacity: 0.45; cursor: default; }
+.fineprint { text-align: center; color: var(--muted); font-size: 11.5px; margin: 8px 0 0; }
diff --git a/hudi-agent-gateway/tests/conftest.py b/hudi-agent-gateway/tests/conftest.py
new file mode 100644
index 000000000000..66b8981bb5ba
--- /dev/null
+++ b/hudi-agent-gateway/tests/conftest.py
@@ -0,0 +1,147 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Shared fixtures: settings, a fake Trino client, and a scripted chat model.
+
+Nothing here talks to a network; the whole suite runs offline.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+from typing import Any
+
+import pytest
+from langchain_core.language_models.fake_chat_models import GenericFakeChatModel
+from langchain_core.messages import AIMessage
+
+from hudi_agent_gateway.config import GatewaySettings
+from hudi_agent_gateway.tools import build_registry
+from hudi_agent_gateway.tools.trino_client import QueryResult, TrinoQueryError
+
+
+@pytest.fixture()
+def settings(monkeypatch: pytest.MonkeyPatch) -> GatewaySettings:
+ # Isolate from the developer's environment.
+ for var in ("ANTHROPIC_API_KEY", "OPENAI_API_KEY"):
+ monkeypatch.delenv(var, raising=False)
+ return GatewaySettings(
+ llm_provider="ollama",
+ trino_host="fake-trino",
+ sql_row_cap=100,
+ tool_result_max_bytes=2000,
+ )
+
+
+class FakeTrinoClient:
+ """Records executed SQL; replays canned results or errors."""
+
+ def __init__(self) -> None:
+ self.executed: list[str] = []
+ self.result = QueryResult(
+ columns=["city", "trips"],
+ rows=[["chennai", 33], ["san_francisco", 34], ["sao_paulo", 33]],
+ )
+ self.error: Exception | None = None
+
+ async def execute(self, sql: str, *, timeout: float, max_rows: int) -> QueryResult:
+ self.executed.append(sql)
+ if self.error is not None:
+ raise self.error
+ return self.result
+
+ async def ping(self, timeout: float = 5.0) -> bool:
+ return self.error is None
+
+ def fail_with(self, message: str) -> None:
+ self.error = TrinoQueryError(message)
+
+
+@pytest.fixture()
+def fake_trino() -> FakeTrinoClient:
+ return FakeTrinoClient()
+
+
+@pytest.fixture()
+def registry(settings: GatewaySettings, fake_trino: FakeTrinoClient):
+ return build_registry(settings, trino_client=fake_trino) # type: ignore[arg-type]
+
+
+class ScriptedChatModel(GenericFakeChatModel):
+ """A fake chat model that replays a fixed sequence of AIMessages, accepts
+ ``bind_tools`` (returning itself), and streams each scripted message as a
+ single chunk -- including tool calls, which the stock fake drops when the
+ message content is empty."""
+
+ def bind_tools(self, tools: Sequence[Any], **kwargs: Any) -> ScriptedChatModel:
+ return self
+
+ def _stream(self, messages: Any, stop: Any = None, run_manager: Any = None, **kwargs: Any):
+ import json as _json
+
+ from langchain_core.messages import AIMessageChunk
+ from langchain_core.outputs import ChatGenerationChunk
+
+ try:
+ message = next(self.messages)
+ except StopIteration:
+ return
+ tool_call_chunks = [
+ {
+ "name": tc["name"],
+ "args": _json.dumps(tc.get("args") or {}),
+ "id": tc.get("id"),
+ "index": i,
+ "type": "tool_call_chunk",
+ }
+ for i, tc in enumerate(getattr(message, "tool_calls", None) or [])
+ ]
+ chunk = AIMessageChunk(content=message.content, tool_call_chunks=tool_call_chunks)
+ yield ChatGenerationChunk(message=chunk)
+
+
+def scripted_model(messages: list[AIMessage]) -> ScriptedChatModel:
+ return ScriptedChatModel(messages=iter(messages))
+
+
+class FixedAgents:
+ """AgentCache stand-in that returns one prebuilt agent for any model."""
+
+ def __init__(self, agent: Any) -> None:
+ self.agent = agent
+ self.requested: list[str | None] = []
+
+ def get(self, model: str | None = None) -> Any:
+ self.requested.append(model)
+ return self.agent
+
+
+TOOL_CALL_THEN_ANSWER = [
+ AIMessage(
+ content="",
+ tool_calls=[
+ {
+ "id": "call_1",
+ "name": "query_lakehouse",
+ "args": {"sql": "SELECT city, count(*) AS trips FROM trips GROUP BY city"},
+ }
+ ],
+ ),
+ AIMessage(
+ content="There are 100 trips across 3 cities: "
+ "chennai 33, san_francisco 34, sao_paulo 33."
+ ),
+]
diff --git a/hudi-agent-gateway/tests/integration/__init__.py b/hudi-agent-gateway/tests/integration/__init__.py
new file mode 100644
index 000000000000..c5a5d9fae9de
--- /dev/null
+++ b/hudi-agent-gateway/tests/integration/__init__.py
@@ -0,0 +1,15 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
diff --git a/hudi-agent-gateway/tests/integration/test_live_stack.py b/hudi-agent-gateway/tests/integration/test_live_stack.py
new file mode 100644
index 000000000000..76c29bc20681
--- /dev/null
+++ b/hudi-agent-gateway/tests/integration/test_live_stack.py
@@ -0,0 +1,93 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Live-stack integration tests, skipped unless the environment provides:
+
+- ``GATEWAY_IT_TRINO_HOST`` (e.g. ``localhost`` with a port-forward to the
+ local-dev hudi-trino service) -- enables the tool tests;
+- additionally ``GATEWAY_IT_LLM=1`` -- enables one real agent round-trip
+ using the gateway's configured provider.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+
+import pytest
+
+from hudi_agent_gateway.config import GatewaySettings
+from hudi_agent_gateway.tools import build_registry
+
+TRINO_HOST = os.environ.get("GATEWAY_IT_TRINO_HOST", "")
+LLM_ENABLED = os.environ.get("GATEWAY_IT_LLM", "") == "1"
+
+pytestmark = pytest.mark.skipif(
+ not TRINO_HOST, reason="set GATEWAY_IT_TRINO_HOST to run live-stack tests"
+)
+
+
+@pytest.fixture()
+def live_settings() -> GatewaySettings:
+ return GatewaySettings(
+ trino_host=TRINO_HOST,
+ trino_port=int(os.environ.get("GATEWAY_IT_TRINO_PORT", "8080")),
+ )
+
+
+@pytest.fixture()
+def live_registry(live_settings: GatewaySettings):
+ return build_registry(live_settings)
+
+
+async def test_list_tables_live(live_registry) -> None:
+ out = json.loads(await live_registry.get("list_tables").handler())
+ tables = [row[1] for row in out["rows"]]
+ assert "trips" in tables
+
+
+async def test_describe_table_live(live_registry) -> None:
+ out = json.loads(await live_registry.get("describe_table").handler(table="trips"))
+ columns = [row[0] for row in out["rows"]]
+ assert {"trip_id", "city", "fare"} <= set(columns)
+
+
+async def test_query_lakehouse_live(live_registry) -> None:
+ out = json.loads(
+ await live_registry.get("query_lakehouse").handler(
+ sql="SELECT city, count(*) AS trips FROM trips GROUP BY city ORDER BY city"
+ )
+ )
+ assert out["row_count"] == 3
+ assert sum(row[1] for row in out["rows"]) == 100
+
+
+@pytest.mark.skipif(not LLM_ENABLED, reason="set GATEWAY_IT_LLM=1 to run the LLM round-trip")
+async def test_agent_round_trip_live(live_settings) -> None:
+ from langgraph.checkpoint.memory import InMemorySaver
+
+ from hudi_agent_gateway.agent import build_agent
+ from hudi_agent_gateway.llm import build_chat_model
+
+ registry = build_registry(live_settings)
+ agent = build_agent(
+ build_chat_model(live_settings), registry, InMemorySaver(), live_settings
+ )
+ result = await agent.ainvoke(
+ {"messages": [("user", "How many rows are in the trips table? Answer with the number.")]},
+ config={"configurable": {"thread_id": "it"}},
+ )
+ assert "100" in result["messages"][-1].text()
diff --git a/hudi-agent-gateway/tests/test_agent_loop.py b/hudi-agent-gateway/tests/test_agent_loop.py
new file mode 100644
index 000000000000..935497212d57
--- /dev/null
+++ b/hudi-agent-gateway/tests/test_agent_loop.py
@@ -0,0 +1,143 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""The real LangGraph agent wired to the real registry with a scripted model."""
+
+from __future__ import annotations
+
+from langchain_core.messages import AIMessage, HumanMessage, ToolMessage
+from langgraph.checkpoint.memory import InMemorySaver
+
+from hudi_agent_gateway.agent import build_agent, build_system_prompt
+from tests.conftest import TOOL_CALL_THEN_ANSWER, scripted_model
+
+
+async def test_loop_executes_tool_and_answers(settings, registry, fake_trino) -> None:
+ agent = build_agent(scripted_model(TOOL_CALL_THEN_ANSWER), registry, InMemorySaver(), settings)
+ result = await agent.ainvoke(
+ {"messages": [HumanMessage("How many trips per city?")]},
+ config={"configurable": {"thread_id": "t1"}},
+ )
+ messages = result["messages"]
+ # The tool actually executed against the fake Trino client...
+ assert fake_trino.executed and "LIMIT" in fake_trino.executed[0]
+ tool_msgs = [m for m in messages if isinstance(m, ToolMessage)]
+ assert len(tool_msgs) == 1
+ assert "chennai" in str(tool_msgs[0].content)
+ # ...and the final answer is the scripted closing message.
+ assert isinstance(messages[-1], AIMessage)
+ assert "100 trips" in messages[-1].text()
+
+
+async def test_checkpointer_preserves_history_across_turns(settings, registry) -> None:
+ saver = InMemorySaver()
+ first = scripted_model(
+ [AIMessage(content="The trips table has 100 rows across 3 cities.")]
+ )
+ agent = build_agent(first, registry, saver, settings)
+ await agent.ainvoke(
+ {"messages": [HumanMessage("How many rows in trips?")]},
+ config={"configurable": {"thread_id": "same-thread"}},
+ )
+ # Second turn on the SAME thread: the model sees prior history.
+ second = scripted_model([AIMessage(content="As I said: 100.")])
+ agent2 = build_agent(second, registry, saver, settings)
+ result = await agent2.ainvoke(
+ {"messages": [HumanMessage("Remind me?")]},
+ config={"configurable": {"thread_id": "same-thread"}},
+ )
+ texts = [m.text() for m in result["messages"] if hasattr(m, "text")]
+ assert any("100 rows across 3 cities" in t for t in texts) # history retained
+ assert len(result["messages"]) >= 4 # two human + two ai
+
+
+def test_system_prompt_interpolation(settings) -> None:
+ prompt = build_system_prompt(settings)
+ assert "`hudi`" in prompt and "`default`" in prompt
+ assert str(settings.sql_row_cap) in prompt
+ assert "markdown tables" in prompt
+
+
+def test_agent_cache_builds_per_model_and_caps(settings, registry) -> None:
+ from langgraph.checkpoint.memory import InMemorySaver
+
+ from hudi_agent_gateway.agent import AgentCache
+
+ cache = AgentCache(registry, InMemorySaver(), settings)
+ default_agent = cache.get(None)
+ assert cache.get(None) is default_agent # cached
+ other = cache.get("some-other-model")
+ assert other is not default_agent # distinct per model
+ for i in range(10): # exceeds the cap without error
+ cache.get(f"m{i}")
+ assert cache.get("m9") is cache.get("m9")
+
+
+async def test_loop_repairs_broken_thinking_block_before_next_model_call(
+ settings, registry
+) -> None:
+ """A streamed adaptive-thinking turn stored with a signature-only thinking
+ block must reach the model repaired on the following loop iteration."""
+ from typing import Any
+
+ from tests.conftest import ScriptedChatModel
+
+ seen: list[list[Any]] = []
+
+ class RecordingModel(ScriptedChatModel):
+ def _stream(self, messages: Any, stop: Any = None, run_manager: Any = None, **kwargs: Any):
+ seen.append(list(messages))
+ yield from super()._stream(messages, stop, run_manager, **kwargs)
+
+ def _generate(self, messages: Any, stop: Any = None, run_manager: Any = None, **kw: Any):
+ seen.append(list(messages))
+ return super()._generate(messages, stop=stop, run_manager=run_manager, **kw)
+
+ model = RecordingModel(messages=iter([
+ AIMessage(
+ content=[{"type": "thinking", "signature": "sig=="}], # no `thinking` key
+ tool_calls=[{"id": "call_1", "name": "list_tables", "args": {}}],
+ ),
+ AIMessage(content="Answer grounded in the listing."),
+ ]))
+ agent = build_agent(model, registry, InMemorySaver(), settings)
+ await agent.ainvoke(
+ {"messages": [HumanMessage("What tables exist?")]},
+ config={"configurable": {"thread_id": "thinking-repair"}},
+ )
+
+ second_call_ai = [m for m in seen[1] if isinstance(m, AIMessage)]
+ blocks = second_call_ai[0].content
+ assert blocks[0]["type"] == "thinking" and blocks[0]["thinking"] == ""
+
+
+def test_repair_thinking_blocks_restores_missing_field() -> None:
+ from hudi_agent_gateway.agent import repair_thinking_blocks
+
+ broken = AIMessage(content=[
+ {"type": "thinking", "signature": "sig=="}, # streamed merge dropped `thinking`
+ {"type": "thinking", "thinking": "kept", "signature": "s2"},
+ {"type": "text", "text": "hi"},
+ ])
+ human = HumanMessage("q")
+ plain = AIMessage(content="just text")
+
+ out = repair_thinking_blocks([human, broken, plain])
+
+ assert out[0] is human and out[2] is plain # untouched passthrough
+ assert out[1].content[0] == {"type": "thinking", "signature": "sig==", "thinking": ""}
+ assert out[1].content[1]["thinking"] == "kept" # present field untouched
+ assert broken.content[0] == {"type": "thinking", "signature": "sig=="} # original not mutated
diff --git a/hudi-agent-gateway/tests/test_api_meta.py b/hudi-agent-gateway/tests/test_api_meta.py
new file mode 100644
index 000000000000..0aeba0c9dc26
--- /dev/null
+++ b/hudi-agent-gateway/tests/test_api_meta.py
@@ -0,0 +1,93 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import httpx
+import pytest
+
+from hudi_agent_gateway.app import create_app
+
+
+@pytest.fixture()
+async def client(settings, fake_trino, monkeypatch):
+ app = create_app(settings.model_copy(update={"mcp_enabled": False}))
+ # The app builds its own TrinoClient; swap in the fake after startup.
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as c, app.router.lifespan_context(app):
+ app.state.trino_client = fake_trino
+ yield c, app
+
+
+async def test_health(client) -> None:
+ c, _ = client
+ resp = await c.get("/health")
+ assert resp.status_code == 200
+ assert resp.json()["status"] == "ok"
+
+
+async def test_ready_reports_dependency_failures(client) -> None:
+ c, app = client
+ app.state.trino_client.fail_with("connection refused")
+
+ class NotReady:
+ async def check(self):
+ return False, "unreachable (http://x)"
+
+ app.state.llm_readiness = NotReady()
+ resp = await c.get("/ready")
+ assert resp.status_code == 503
+ body = resp.json()
+ assert body["ready"] is False
+ assert body["checks"]["trino"]["ok"] is False
+ assert body["checks"]["llm"]["ok"] is False
+
+
+async def test_ready_ok(client) -> None:
+ c, app = client
+
+ class Ready:
+ async def check(self):
+ return True, "reachable"
+
+ app.state.llm_readiness = Ready()
+ resp = await c.get("/ready")
+ assert resp.status_code == 200
+ assert resp.json()["ready"] is True
+
+
+async def test_tools_listing(client) -> None:
+ c, _ = client
+ resp = await c.get("/v1/tools")
+ tools = resp.json()["tools"]
+ assert {t["name"] for t in tools} == {"query_lakehouse", "list_tables", "describe_table"}
+ for tool in tools:
+ assert tool["description"]
+ assert "properties" in tool["input_schema"]
+
+
+async def test_info(client) -> None:
+ c, _ = client
+ resp = await c.get("/v1/info")
+ body = resp.json()
+ assert body["name"] == "hudi-agent-gateway"
+ assert body["provider"] == "ollama"
+ assert body["catalog"] == "hudi"
+ assert body["schema"] == "default"
+ assert body["trino_url"] == "http://fake-trino:8080"
+ assert body["trino_ui_url"] == "http://fake-trino:8080/ui/"
+ assert body["mcp_enabled"] is False # fixture disables MCP
diff --git a/hudi-agent-gateway/tests/test_chat_sse.py b/hudi-agent-gateway/tests/test_chat_sse.py
new file mode 100644
index 000000000000..92f68bbdbcc4
--- /dev/null
+++ b/hudi-agent-gateway/tests/test_chat_sse.py
@@ -0,0 +1,134 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""/v1/chat behavior with a scripted model: JSON path and SSE event stream."""
+
+from __future__ import annotations
+
+import json
+
+import httpx
+import pytest
+from langchain_core.messages import AIMessage
+
+from hudi_agent_gateway.agent import build_agent
+from hudi_agent_gateway.app import create_app
+from tests.conftest import TOOL_CALL_THEN_ANSWER, FixedAgents, scripted_model
+
+
+@pytest.fixture()
+async def client(settings, registry, fake_trino):
+ app = create_app(settings.model_copy(update={"mcp_enabled": False}))
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as c, app.router.lifespan_context(app):
+ app.state.trino_client = fake_trino
+ app.state.registry = registry
+ app.state.agents = FixedAgents(
+ build_agent(
+ scripted_model(TOOL_CALL_THEN_ANSWER),
+ registry,
+ app.state.sessions.checkpointer,
+ settings,
+ )
+ )
+ yield c, app
+
+
+def _parse_sse(text: str) -> list[tuple[str, dict]]:
+ events: list[tuple[str, dict]] = []
+ text = text.replace("\r\n", "\n")
+ for frame in text.split("\n\n"):
+ event, data = "message", []
+ for line in frame.split("\n"):
+ if line.startswith("event:"):
+ event = line[6:].strip()
+ elif line.startswith("data:"):
+ data.append(line[5:].strip())
+ if data:
+ events.append((event, json.loads("\n".join(data))))
+ return events
+
+
+async def test_non_streaming_chat_returns_trace(client) -> None:
+ c, _ = client
+ resp = await c.post(
+ "/v1/chat", json={"message": "trips per city?", "session_id": "s-json"}
+ )
+ assert resp.status_code == 200
+ body = resp.json()
+ assert "100 trips" in body["message"]
+ assert body["session_id"] == "s-json"
+ assert len(body["tool_trace"]) == 1
+ trace = body["tool_trace"][0]
+ assert trace["name"] == "query_lakehouse"
+ assert "sql" in trace["args"]
+ assert "chennai" in trace["result_preview"]
+ assert trace["is_error"] is False
+
+
+async def test_streaming_chat_event_order(client) -> None:
+ c, _ = client
+ resp = await c.post(
+ "/v1/chat",
+ json={"message": "trips per city?", "session_id": "s-sse", "stream": True},
+ )
+ assert resp.status_code == 200
+ assert resp.headers["content-type"].startswith("text/event-stream")
+ events = _parse_sse(resp.text)
+ kinds = [e for e, _ in events]
+
+ assert "tool_call" in kinds and "tool_result" in kinds and kinds[-1] == "done"
+ assert kinds.index("tool_call") < kinds.index("tool_result")
+
+ tool_call = next(d for e, d in events if e == "tool_call")
+ assert tool_call["name"] == "query_lakehouse"
+ tool_result = next(d for e, d in events if e == "tool_result")
+ assert "chennai" in tool_result["preview"]
+ done = events[-1][1]
+ assert "100 trips" in done["message"]
+ # token events accumulate to the same final text
+ tokens = "".join(d["text"] for e, d in events if e == "token")
+ assert tokens == done["message"]
+
+
+async def test_streaming_error_event_on_model_failure(client, settings, registry) -> None:
+ c, app = client
+
+ class ExplodingModel(type(scripted_model([AIMessage(content="x")]))):
+ def _generate(self, *args, **kwargs):
+ raise RuntimeError("model exploded")
+
+ async def _agenerate(self, *args, **kwargs):
+ raise RuntimeError("model exploded")
+
+ app.state.agents = FixedAgents(
+ build_agent(
+ ExplodingModel(messages=iter([])), registry, app.state.sessions.checkpointer, settings
+ )
+ )
+ resp = await c.post(
+ "/v1/chat", json={"message": "boom", "session_id": "s-err", "stream": True}
+ )
+ events = _parse_sse(resp.text)
+ assert events[-1][0] == "error"
+ assert events[-1][1]["code"] == "agent_error"
+
+
+async def test_validation_rejects_empty_message(client) -> None:
+ c, _ = client
+ resp = await c.post("/v1/chat", json={"message": "", "session_id": "s"})
+ assert resp.status_code == 422
diff --git a/hudi-agent-gateway/tests/test_config.py b/hudi-agent-gateway/tests/test_config.py
new file mode 100644
index 000000000000..c1ccedeb4f5a
--- /dev/null
+++ b/hudi-agent-gateway/tests/test_config.py
@@ -0,0 +1,76 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import pytest
+from pydantic import ValidationError
+
+from hudi_agent_gateway.config import GatewaySettings
+
+
+@pytest.fixture(autouse=True)
+def _clean_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ for var in ("ANTHROPIC_API_KEY", "OPENAI_API_KEY"):
+ monkeypatch.delenv(var, raising=False)
+
+
+def test_defaults() -> None:
+ s = GatewaySettings()
+ assert s.llm_provider == "ollama"
+ assert s.trino_catalog == "hudi"
+ assert s.sql_row_cap == 200
+ assert s.port == 8000
+
+
+def test_env_prefix(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("GATEWAY_SQL_ROW_CAP", "42")
+ monkeypatch.setenv("GATEWAY_TRINO_HOST", "example")
+ s = GatewaySettings()
+ assert s.sql_row_cap == 42
+ assert s.trino_host == "example"
+
+
+def test_invalid_provider_rejected() -> None:
+ with pytest.raises(ValidationError):
+ GatewaySettings(llm_provider="bedrock") # type: ignore[arg-type]
+
+
+def test_anthropic_requires_key() -> None:
+ with pytest.raises(ValidationError, match="ANTHROPIC_API_KEY"):
+ GatewaySettings(llm_provider="anthropic")
+
+
+def test_openai_requires_key() -> None:
+ with pytest.raises(ValidationError, match="OPENAI_API_KEY"):
+ GatewaySettings(llm_provider="openai")
+
+
+def test_openai_compatible_requires_base_url() -> None:
+ with pytest.raises(ValidationError, match="GATEWAY_OPENAI_BASE_URL"):
+ GatewaySettings(llm_provider="openai-compatible")
+
+
+def test_unprefixed_api_key_alias(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("ANTHROPIC_API_KEY", "sk-test")
+ s = GatewaySettings(llm_provider="anthropic")
+ assert s.anthropic_api_key == "sk-test"
+
+
+def test_prefixed_api_key_alias(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("GATEWAY_OPENAI_API_KEY", "sk-test2")
+ s = GatewaySettings(llm_provider="openai")
+ assert s.openai_api_key == "sk-test2"
diff --git a/hudi-agent-gateway/tests/test_guardrails.py b/hudi-agent-gateway/tests/test_guardrails.py
new file mode 100644
index 000000000000..d7c610c511b1
--- /dev/null
+++ b/hudi-agent-gateway/tests/test_guardrails.py
@@ -0,0 +1,104 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""AST-level SQL guardrail behavior: read-only enforcement + LIMIT capping."""
+
+from __future__ import annotations
+
+import pytest
+
+from hudi_agent_gateway.tools.guardrails import enforce_guardrails
+from hudi_agent_gateway.tools.registry import ToolInputError
+
+CAP = 100
+
+
+def test_plain_select_gets_limit_injected() -> None:
+ out = enforce_guardrails("SELECT a FROM t", row_cap=CAP)
+ assert f"LIMIT {CAP}" in out
+
+
+def test_existing_smaller_limit_is_preserved() -> None:
+ out = enforce_guardrails("SELECT a FROM t LIMIT 10", row_cap=CAP)
+ assert "LIMIT 10" in out and f"LIMIT {CAP}" not in out
+
+
+def test_oversized_limit_is_lowered() -> None:
+ out = enforce_guardrails("SELECT a FROM t LIMIT 100000", row_cap=CAP)
+ assert f"LIMIT {CAP}" in out and "100000" not in out
+
+
+def test_cte_select_is_allowed() -> None:
+ out = enforce_guardrails("WITH x AS (SELECT a FROM t) SELECT * FROM x", row_cap=CAP)
+ assert out.upper().startswith("WITH") and f"LIMIT {CAP}" in out
+
+
+def test_union_is_allowed_and_capped() -> None:
+ out = enforce_guardrails("SELECT a FROM t UNION ALL SELECT a FROM u", row_cap=CAP)
+ assert "UNION" in out.upper() and f"LIMIT {CAP}" in out
+
+
+@pytest.mark.parametrize(
+ "sql",
+ [
+ "INSERT INTO t VALUES (1)",
+ "UPDATE t SET a = 1",
+ "DELETE FROM t",
+ "MERGE INTO t USING u ON t.id = u.id WHEN MATCHED THEN UPDATE SET a = 1",
+ "CREATE TABLE t2 AS SELECT * FROM t",
+ "DROP TABLE t",
+ "TRUNCATE TABLE t",
+ "GRANT SELECT ON t TO alice",
+ "SET SESSION query_max_run_time = '1m'",
+ "EXPLAIN SELECT 1",
+ "CALL system.runtime.kill_query('q')",
+ "USE hudi.default",
+ ],
+)
+def test_non_select_statements_are_rejected(sql: str) -> None:
+ with pytest.raises(ToolInputError):
+ enforce_guardrails(sql, row_cap=CAP)
+
+
+def test_select_wrapping_dml_is_rejected() -> None:
+ # SELECT-rooted, so only the defense-in-depth tree walk can catch it.
+ with pytest.raises(ToolInputError, match="Insert"):
+ enforce_guardrails("WITH t AS (INSERT INTO x VALUES (1)) SELECT * FROM t", row_cap=CAP)
+
+
+def test_multiple_statements_are_rejected() -> None:
+ with pytest.raises(ToolInputError, match="one statement"):
+ enforce_guardrails("SELECT 1; SELECT 2", row_cap=CAP)
+
+
+def test_garbage_is_rejected() -> None:
+ with pytest.raises(ToolInputError):
+ enforce_guardrails("please show me the data", row_cap=CAP)
+
+
+def test_comment_smuggled_dml_is_rejected() -> None:
+ with pytest.raises(ToolInputError):
+ enforce_guardrails("/* harmless */ DELETE FROM t -- SELECT", row_cap=CAP)
+
+
+def test_string_literal_containing_dml_is_fine() -> None:
+ out = enforce_guardrails("SELECT 'DELETE FROM t' AS s", row_cap=CAP)
+ assert "DELETE FROM t" in out # inside the literal
+
+
+def test_quoted_identifiers_round_trip() -> None:
+ out = enforce_guardrails('SELECT "weird col" FROM "my table"', row_cap=CAP)
+ assert '"weird col"' in out
diff --git a/hudi-agent-gateway/tests/test_llm.py b/hudi-agent-gateway/tests/test_llm.py
new file mode 100644
index 000000000000..49d7f10a5b59
--- /dev/null
+++ b/hudi-agent-gateway/tests/test_llm.py
@@ -0,0 +1,114 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import pytest
+from langchain_anthropic import ChatAnthropic
+from langchain_ollama import ChatOllama
+from langchain_openai import ChatOpenAI
+
+from hudi_agent_gateway.config import GatewaySettings
+from hudi_agent_gateway.llm import LLMReadiness, build_chat_model
+
+
+@pytest.fixture(autouse=True)
+def _clean_env(monkeypatch: pytest.MonkeyPatch) -> None:
+ for var in ("ANTHROPIC_API_KEY", "OPENAI_API_KEY"):
+ monkeypatch.delenv(var, raising=False)
+
+
+def test_anthropic_factory() -> None:
+ s = GatewaySettings(
+ llm_provider="anthropic", llm_model="claude-sonnet-5", anthropic_api_key="sk-x"
+ )
+ model = build_chat_model(s)
+ assert isinstance(model, ChatAnthropic)
+
+
+def test_openai_factory() -> None:
+ s = GatewaySettings(llm_provider="openai", llm_model="gpt-4o", openai_api_key="sk-x")
+ assert isinstance(build_chat_model(s), ChatOpenAI)
+
+
+def test_ollama_factory_plumbs_base_url() -> None:
+ s = GatewaySettings(
+ llm_provider="ollama", llm_model="qwen3:8b", ollama_base_url="http://host:11434"
+ )
+ model = build_chat_model(s)
+ assert isinstance(model, ChatOllama)
+ assert model.base_url == "http://host:11434"
+
+
+def test_openai_compatible_factory_plumbs_base_url() -> None:
+ s = GatewaySettings(
+ llm_provider="openai-compatible",
+ llm_model="my-vllm-model",
+ openai_base_url="http://vllm:8000/v1",
+ )
+ model = build_chat_model(s)
+ assert isinstance(model, ChatOpenAI)
+ assert str(model.openai_api_base) == "http://vllm:8000/v1"
+
+
+async def test_hosted_provider_ready_without_network() -> None:
+ s = GatewaySettings(llm_provider="anthropic", anthropic_api_key="sk-x")
+ ok, detail = await LLMReadiness(s).check()
+ assert ok and "key" in detail
+
+
+async def test_local_provider_unreachable_reports_not_ready() -> None:
+ s = GatewaySettings(llm_provider="ollama", ollama_base_url="http://127.0.0.1:1")
+ ok, detail = await LLMReadiness(s).check()
+ assert not ok and "unreachable" in detail
+
+
+async def test_list_models_ollama(monkeypatch, httpx_ollama_tags=None) -> None:
+ import httpx
+
+ from hudi_agent_gateway import llm as llm_mod
+
+ async def fake_get(self, url, **kwargs):
+ assert url.endswith("/api/tags")
+ request = httpx.Request("GET", url)
+ return httpx.Response(
+ 200, json={"models": [{"name": "qwen3:4b"}, {"name": "llama3.2:3b"}]}, request=request
+ )
+
+ monkeypatch.setattr(httpx.AsyncClient, "get", fake_get)
+ s = GatewaySettings(llm_provider="ollama", llm_model="qwen3:4b")
+ models = await llm_mod.list_models(s)
+ assert models[0] == "qwen3:4b" # configured default first
+ assert "llama3.2:3b" in models
+
+
+async def test_list_models_falls_back_to_default(monkeypatch) -> None:
+ import httpx
+
+ from hudi_agent_gateway import llm as llm_mod
+
+ async def exploding_get(self, url, **kwargs):
+ raise httpx.ConnectError("nope")
+
+ monkeypatch.setattr(httpx.AsyncClient, "get", exploding_get)
+ s = GatewaySettings(llm_provider="ollama", llm_model="qwen3:4b")
+ assert await llm_mod.list_models(s) == ["qwen3:4b"]
+
+
+def test_build_chat_model_override() -> None:
+ s = GatewaySettings(llm_provider="ollama", llm_model="qwen3:4b")
+ model = build_chat_model(s, model="qwen3:8b")
+ assert model.model == "qwen3:8b"
diff --git a/hudi-agent-gateway/tests/test_mcp.py b/hudi-agent-gateway/tests/test_mcp.py
new file mode 100644
index 000000000000..f1455acc8b83
--- /dev/null
+++ b/hudi-agent-gateway/tests/test_mcp.py
@@ -0,0 +1,78 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""The MCP surface, including the mounted-app lifespan regression."""
+
+from __future__ import annotations
+
+import json
+
+import httpx
+from fastmcp import Client
+
+from hudi_agent_gateway.app import create_app
+from hudi_agent_gateway.mcp_server import build_mcp
+
+
+async def test_mcp_lists_and_calls_tools(registry) -> None:
+ mcp = build_mcp(registry)
+ async with Client(mcp) as client:
+ tools = await client.list_tools()
+ assert {t.name for t in tools} == {"query_lakehouse", "list_tables", "describe_table"}
+ result = await client.call_tool(
+ "query_lakehouse", {"sql": "SELECT city, count(*) FROM trips GROUP BY city"}
+ )
+ payload = json.loads(result.content[0].text)
+ assert payload["row_count"] == 3
+
+
+async def test_mounted_mcp_serves_over_http(settings, fake_trino) -> None:
+ """Regression for the FastMCP lifespan gotcha: without running the MCP
+ sub-app's lifespan inside the outer app's, /mcp requests hang/fail."""
+ app = create_app(settings)
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as c, app.router.lifespan_context(app):
+ app.state.trino_client = fake_trino
+ resp = await c.post(
+ "/mcp/",
+ json={
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "initialize",
+ "params": {
+ "protocolVersion": "2025-06-18",
+ "capabilities": {},
+ "clientInfo": {"name": "test", "version": "0"},
+ },
+ },
+ headers={
+ "Accept": "application/json, text/event-stream",
+ "Content-Type": "application/json",
+ },
+ )
+ assert resp.status_code == 200
+ assert "hudi-lakehouse" in resp.text
+
+
+async def test_mcp_disabled(settings, fake_trino) -> None:
+ settings = settings.model_copy(update={"mcp_enabled": False})
+ app = create_app(settings)
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as c, app.router.lifespan_context(app):
+ resp = await c.post("/mcp/", json={})
+ assert resp.status_code == 404
diff --git a/hudi-agent-gateway/tests/test_registry.py b/hudi-agent-gateway/tests/test_registry.py
new file mode 100644
index 000000000000..21d600b93185
--- /dev/null
+++ b/hudi-agent-gateway/tests/test_registry.py
@@ -0,0 +1,100 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Define-once, expose-twice: LangChain and MCP derive from one registration."""
+
+from __future__ import annotations
+
+import json
+import logging
+from typing import Annotated
+
+import pytest
+from fastmcp import Client, FastMCP
+from pydantic import Field
+
+from hudi_agent_gateway.tools.registry import ToolRegistry, is_tool_error
+
+
+@pytest.fixture()
+def simple_registry() -> ToolRegistry:
+ registry = ToolRegistry()
+
+ @registry.register("echo_tool", "Echoes its input.")
+ async def echo_tool(
+ text: Annotated[str, Field(description="Text to echo back.")],
+ ) -> str:
+ return json.dumps({"echo": text})
+
+ return registry
+
+
+def test_langchain_derivation(simple_registry: ToolRegistry) -> None:
+ tools = simple_registry.langchain_tools()
+ assert len(tools) == 1
+ tool = tools[0]
+ assert tool.name == "echo_tool"
+ assert tool.description == "Echoes its input."
+ schema = tool.tool_call_schema.model_json_schema()
+ assert schema["properties"]["text"]["description"] == "Text to echo back."
+ assert schema["required"] == ["text"]
+
+
+async def test_mcp_derivation_matches(simple_registry: ToolRegistry) -> None:
+ mcp: FastMCP = FastMCP("test")
+ simple_registry.attach_to_mcp(mcp)
+ async with Client(mcp) as client:
+ tools = await client.list_tools()
+ assert [t.name for t in tools] == ["echo_tool"]
+ assert tools[0].description == "Echoes its input."
+ assert tools[0].inputSchema["properties"]["text"]["description"] == "Text to echo back."
+
+
+async def test_same_payload_via_both_paths(simple_registry: ToolRegistry) -> None:
+ lc_result = await simple_registry.langchain_tools()[0].ainvoke({"text": "hi"})
+
+ mcp: FastMCP = FastMCP("test")
+ simple_registry.attach_to_mcp(mcp)
+ async with Client(mcp) as client:
+ mcp_result = await client.call_tool("echo_tool", {"text": "hi"})
+ assert json.loads(lc_result) == {"echo": "hi"}
+ assert json.loads(mcp_result.content[0].text) == {"echo": "hi"}
+
+
+async def test_invocation_logged_once(
+ simple_registry: ToolRegistry, caplog: pytest.LogCaptureFixture
+) -> None:
+ with caplog.at_level(logging.INFO, logger="hudi_agent_gateway.tools"):
+ await simple_registry.get("echo_tool").handler(text="hi")
+ records = [r for r in caplog.records if r.getMessage() == "tool_invocation"]
+ assert len(records) == 1
+ fields = records[0].extra_fields # type: ignore[attr-defined]
+ assert fields["tool"] == "echo_tool"
+ assert fields["outcome"] == "ok"
+ assert fields["duration_ms"] >= 0
+
+
+def test_duplicate_registration_rejected(simple_registry: ToolRegistry) -> None:
+ with pytest.raises(ValueError, match="already registered"):
+ simple_registry.register("echo_tool", "dup")
+
+
+def test_is_tool_error_parses_not_substring_matches() -> None:
+ assert is_tool_error(json.dumps({"error": "boom", "hint": "fix it"}))
+ # a successful result whose DATA mentions "error" (e.g. a column named
+ # `error`) is not an error
+ assert not is_tool_error(json.dumps({"columns": ["error"], "rows": [[1]]}))
+ assert not is_tool_error("not json at all")
diff --git a/hudi-agent-gateway/tests/test_sessions.py b/hudi-agent-gateway/tests/test_sessions.py
new file mode 100644
index 000000000000..5396f1dd242b
--- /dev/null
+++ b/hudi-agent-gateway/tests/test_sessions.py
@@ -0,0 +1,68 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import time
+
+from hudi_agent_gateway.config import GatewaySettings
+from hudi_agent_gateway.sessions import SessionStore
+
+
+def _store(**overrides: object) -> SessionStore:
+ settings = GatewaySettings(
+ llm_provider="ollama",
+ **overrides, # type: ignore[arg-type]
+ )
+ return SessionStore(settings)
+
+
+def test_touch_tracks_sessions() -> None:
+ store = _store()
+ store.touch("a")
+ store.touch("b")
+ assert store.active_sessions == 2
+
+
+def test_ttl_sweep_evicts_idle_sessions(monkeypatch) -> None:
+ store = _store(session_ttl_seconds=10.0)
+ store.touch("old")
+ # Age the session by shifting the recorded time back.
+ store._last_access["old"] = time.monotonic() - 60.0
+ store.touch("fresh")
+ evicted = store.sweep()
+ assert evicted == 1
+ assert store.active_sessions == 1
+ assert "fresh" in store._last_access
+
+
+def test_lru_eviction_beyond_max_sessions() -> None:
+ store = _store(max_sessions=3)
+ for sid in ("a", "b", "c"):
+ store.touch(sid)
+ store.touch("d") # exceeds the cap; "a" is oldest
+ assert store.active_sessions == 3
+ assert "a" not in store._last_access
+
+
+def test_last_access_refresh_prevents_eviction() -> None:
+ store = _store(max_sessions=3)
+ for sid in ("a", "b", "c"):
+ store.touch(sid)
+ store.touch("a") # refresh: now "b" is oldest
+ store.touch("d")
+ assert "a" in store._last_access
+ assert "b" not in store._last_access
diff --git a/hudi-agent-gateway/tests/test_trino_tools.py b/hudi-agent-gateway/tests/test_trino_tools.py
new file mode 100644
index 000000000000..7b19731ba984
--- /dev/null
+++ b/hudi-agent-gateway/tests/test_trino_tools.py
@@ -0,0 +1,134 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+from __future__ import annotations
+
+import json
+
+from hudi_agent_gateway.tools.registry import ToolRegistry
+from hudi_agent_gateway.tools.trino_client import QueryResult
+from hudi_agent_gateway.tools.trino_tools import shape_result
+
+
+async def _call(registry: ToolRegistry, name: str, **kwargs: object) -> dict:
+ return json.loads(await registry.get(name).handler(**kwargs))
+
+
+async def test_query_lakehouse_shapes_result(registry: ToolRegistry, fake_trino) -> None:
+ out = await _call(registry, "query_lakehouse", sql="SELECT city FROM trips")
+ assert out["columns"] == ["city", "trips"]
+ assert out["row_count"] == 3
+ assert out["truncated"] is False
+ # the guardrail-injected LIMIT reached the client
+ assert "LIMIT 100" in fake_trino.executed[0]
+
+
+async def test_query_lakehouse_guardrail_error_returned_not_raised(registry: ToolRegistry) -> None:
+ out = await _call(registry, "query_lakehouse", sql="DROP TABLE trips")
+ assert "error" in out and "read-only" in out["error"]
+ assert "hint" in out
+
+
+async def test_query_lakehouse_trino_error_returned(registry: ToolRegistry, fake_trino) -> None:
+ fake_trino.fail_with("SYNTAX_ERROR: line 1: mismatched input")
+ out = await _call(registry, "query_lakehouse", sql="SELECT nope FROM trips")
+ assert out["error"].startswith("query failed")
+
+
+async def test_query_lakehouse_timeout_gets_actionable_hint(
+ registry: ToolRegistry, fake_trino
+) -> None:
+ """Timeouts must NOT get the generic 'fix the SQL' hint -- the SQL is fine."""
+ from hudi_agent_gateway.tools.trino_client import TrinoTimeoutError
+
+ fake_trino.error = TrinoTimeoutError("query exceeded the 120s timeout")
+ out = await _call(registry, "query_lakehouse", sql="SELECT count(*) FROM trips")
+ assert out["error"].startswith("query failed")
+ assert "GATEWAY_SQL_TIMEOUT_SECONDS" in out["hint"]
+ assert "Fix the SQL" not in out["hint"]
+
+
+async def test_truncation_notice(registry: ToolRegistry, fake_trino) -> None:
+ fake_trino.result = QueryResult(
+ columns=["s"], rows=[["x" * 100] for _ in range(200)]
+ )
+ out = await _call(registry, "query_lakehouse", sql="SELECT s FROM big")
+ assert out["truncated"] is True
+ assert "notice" in out
+ assert out["row_count"] == 200 # original fetched count is preserved
+ assert len(out["rows"]) < 200
+
+
+async def test_row_capped_result_reports_truncated(registry: ToolRegistry, fake_trino) -> None:
+ """A result that filled the row cap is truncated even when it fits in bytes."""
+ fake_trino.result = QueryResult(columns=["c"], rows=[["v"] for _ in range(100)])
+ out = await _call(registry, "query_lakehouse", sql="SELECT c FROM big")
+ assert out["truncated"] is True
+ assert "row cap" in out["notice"]
+ assert len(out["rows"]) == 100 # the byte-size loop did not fire
+
+
+async def test_list_tables_defaults(registry: ToolRegistry, fake_trino) -> None:
+ await _call(registry, "list_tables")
+ sql = fake_trino.executed[0]
+ assert '"hudi".information_schema.tables' in sql
+ assert "table_schema = 'default'" in sql
+
+
+async def test_list_tables_explicit(registry: ToolRegistry, fake_trino) -> None:
+ await _call(registry, "list_tables", catalog="other", schema_name="s2")
+ sql = fake_trino.executed[0]
+ assert '"other".information_schema.tables' in sql
+ assert "table_schema = 's2'" in sql
+
+
+async def test_describe_table_name_forms(registry: ToolRegistry, fake_trino) -> None:
+ await _call(registry, "describe_table", table="trips")
+ assert '"hudi".information_schema.columns' in fake_trino.executed[0]
+ await _call(registry, "describe_table", table="cat.sch.trips")
+ assert '"cat".information_schema.columns' in fake_trino.executed[1]
+ out = await _call(registry, "describe_table", table="a.b.c.d")
+ assert "error" in out
+
+
+async def test_describe_missing_table(registry: ToolRegistry, fake_trino) -> None:
+ fake_trino.result = QueryResult(columns=["column_name"], rows=[])
+ out = await _call(registry, "describe_table", table="ghost")
+ assert "not found" in out["error"]
+
+
+async def test_identifier_injection_rejected(registry: ToolRegistry, fake_trino) -> None:
+ """Quoted breakouts in catalog/schema/table params return errors, never reach Trino."""
+ out = await _call(registry, "list_tables", catalog='hudi" --', schema_name="default")
+ assert "invalid catalog name" in out["error"]
+ out = await _call(registry, "list_tables", schema_name="x' OR '1'='1")
+ assert "invalid schema name" in out["error"]
+ out = await _call(registry, "describe_table", table="a.b.c'; DROP TABLE t --")
+ assert "invalid table name" in out["error"]
+ assert fake_trino.executed == [] # nothing was ever sent
+
+
+async def test_shape_result_failsafe_when_metadata_exceeds_cap() -> None:
+ """Zero rows left but payload still too big -> bounded fallback payload."""
+ result = QueryResult(columns=[f"col_{i}" for i in range(500)], rows=[["v"] * 500])
+ text = shape_result(result, max_bytes=400, sql="SELECT " + "x" * 5000, row_cap=100)
+ assert len(text.encode()) <= 400
+ body = json.loads(text)
+ assert body["truncated"] is True and body["rows"] == []
+ assert body["column_count"] == 500
+ # extreme cap: degrades to a bare bounded error payload
+ tiny = shape_result(result, max_bytes=80, sql="SELECT 1", row_cap=100)
+ assert len(tiny.encode()) <= 80 and json.loads(tiny)["truncated"] is True
diff --git a/hudi-agent-gateway/tests/test_ui.py b/hudi-agent-gateway/tests/test_ui.py
new file mode 100644
index 000000000000..b1583bd3b416
--- /dev/null
+++ b/hudi-agent-gateway/tests/test_ui.py
@@ -0,0 +1,77 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""The chat UI: served from the package, self-contained (no external URLs)."""
+
+from __future__ import annotations
+
+import re
+
+import httpx
+import pytest
+
+from hudi_agent_gateway.app import create_app
+
+
+@pytest.fixture()
+async def client(settings):
+ app = create_app(settings.model_copy(update={"mcp_enabled": False}))
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://test"
+ ) as c, app.router.lifespan_context(app):
+ yield c
+
+
+async def test_root_redirects_to_ui(client) -> None:
+ resp = await client.get("/")
+ assert resp.status_code == 307
+ assert resp.headers["location"] == "/ui/"
+
+
+async def test_ui_serves_index(client) -> None:
+ resp = await client.get("/ui/")
+ assert resp.status_code == 200
+ assert "text/html" in resp.headers["content-type"]
+ assert "Hudi Agent Gateway" in resp.text
+
+
+@pytest.mark.parametrize(
+ ("asset", "content_type"),
+ [("app.js", "text/javascript"), ("markdown.js", "text/javascript"), ("style.css", "text/css")],
+)
+async def test_ui_assets_served_with_content_types(client, asset: str, content_type: str) -> None:
+ resp = await client.get(f"/ui/{asset}")
+ assert resp.status_code == 200
+ assert content_type in resp.headers["content-type"]
+
+
+async def test_ui_is_self_contained(client) -> None:
+ """License/air-gap regression: no third-party origins in the UI.
+
+ Sole exception: the Hudi logo image is hotlinked from hudi.apache.org
+ (like the root README) instead of vendoring a binary; offline it degrades
+ to alt text. Code (scripts/styles) must stay strictly local.
+ """
+ index = (await client.get("/ui/")).text
+ refs = re.findall(r'(?:src|href)="([^"]+)"', index)
+ for ref in refs:
+ if ref.startswith("https://hudi.apache.org/"):
+ continue
+ assert not ref.startswith(("http://", "https://", "//")), f"external ref: {ref}"
+ for asset in ("app.js", "markdown.js", "style.css"):
+ body = (await client.get(f"/ui/{asset}")).text
+ assert "https://cdn" not in body
+ assert "@import" not in body
diff --git a/hudi-lakehouse/.gitignore b/hudi-lakehouse/.gitignore
new file mode 100644
index 000000000000..2a443c76b893
--- /dev/null
+++ b/hudi-lakehouse/.gitignore
@@ -0,0 +1,5 @@
+target/
+*.tgz
+Chart.lock
+charts/*/charts/
+.tools/
diff --git a/hudi-lakehouse/README.md b/hudi-lakehouse/README.md
new file mode 100644
index 000000000000..98cafbfdc89d
--- /dev/null
+++ b/hudi-lakehouse/README.md
@@ -0,0 +1,128 @@
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+# hudi-lakehouse
+
+Kubernetes packaging for running a Hudi lakehouse: deployable Helm charts for
+the components, plus a self-contained laptop environment to develop against.
+
+## Quickstart (one command)
+
+Prereqs: `docker`, `minikube`, `helm`, `kubectl`, `mvn`, a JDK (11/17 for the
+Hudi build; a JDK 23 for the Trino connector is auto-provisioned if missing).
+
+```bash
+./hudi-lakehouse/scripts/quickstart.sh --run-example
+```
+
+The script is **idempotent** — run it as many times as you like; every step
+(minikube, maven artifacts, container images, Kubernetes releases) checks
+whether its work is already done and converges. It brings up MinIO, a Hive
+Metastore, the Apache Spark Kubernetes Operator, and Trino with the Hudi
+connector; `--run-example` additionally runs a Spark job that writes a Hudi
+table, registers it in the metastore, and queries it back through Trino:
+
+```
+ city | trips
+---------------+-------
+ chennai | 33
+ san_francisco | 34
+ sao_paulo | 33
+```
+
+Tear down with `./hudi-lakehouse/local-dev/scripts/down.sh`.
+
+## Layout: two separated concerns
+
+A lakehouse is a decoupled architecture — writers, object storage, the
+catalog, and query engines are independent. This directory keeps the
+*deployable product* separate from the *development scaffolding*:
+
+1. **`charts/` — product charts.** Components you install against **real**
+ infrastructure. Each chart deploys one component and points at the others
+ via values.
+
+ | Chart | What it deploys | Points at |
+ |---|---|---|
+ | `hudi-trino` | Trino (server 472) with the Hudi connector built from this repository | your Hive Metastore or AWS Glue; your S3/GCS |
+ | `hudi-agent-gateway` | the [Hudi AI gateway](../hudi-agent-gateway): agent chat API (sessions + SSE), MCP server, and chat UI over guarded lakehouse tools | your `hudi-trino`; your LLM (see below) |
+ | `vllm` | optional: vLLM serving one open-weight model (default `Qwen/Qwen3-8B`, ungated) behind an OpenAI-compatible API; GPU required | — (the gateway points at it) |
+
+ **LLM out-of-box experience**: the gateway defaults to **Ollama**
+ everywhere (zero-setup local models). Switching is a values change:
+ `gateway.provider=anthropic` or `openai` plus an API key (Secret with
+ standard env-var key names, mounted via envFrom — future providers like
+ Together/Fireworks/Baseten need no chart changes), or install the `vllm`
+ chart and set `gateway.provider=openai-compatible` pointing at it. The
+ chat UI discovers whatever the deployment is configured with and offers
+ that provider's models in a picker.
+
+2. **`local-dev/` — a laptop environment.** Minikube scaffolding that stands
+ up everything the charts point at (MinIO, a Derby-backed Hive Metastore,
+ the Spark operator), installs the same `hudi-trino` chart with local
+ values, and ships a copy-me [`example/`](local-dev/example) for submitting
+ Spark jobs. Details: [`local-dev/README.md`](local-dev/README.md).
+
+## Scripts
+
+| Script | Purpose |
+|---|---|
+| `scripts/quickstart.sh` | one-command idempotent bring-up (everything below, in order) |
+| `scripts/build-jars.sh` | maven builds: hudi-spark bundle (JDK 11/17) + hudi-trino-plugin (JDK 23) |
+| `scripts/build-images.sh` | stages jars and builds the two container images; `--registry`/`--push` for clusters |
+| `local-dev/scripts/up.sh` | manifests + spark-operator + hudi-trino chart onto the current kube context |
+| `local-dev/scripts/run-example.sh` | uploads the example job and submits it as a `SparkApplication` |
+| `local-dev/scripts/smoke-test.sh` | end-to-end assert: up → example → Trino row counts |
+| `local-dev/scripts/down.sh` | full teardown |
+
+## Deploying `hudi-trino` against real infrastructure
+
+```bash
+# build + push the image, then:
+./hudi-lakehouse/scripts/build-jars.sh
+./hudi-lakehouse/scripts/build-images.sh --registry my.registry/team --push
+
+helm install hudi-trino hudi-lakehouse/charts/hudi-trino \
+ --set image.repository=my.registry/team/hudi-lakehouse-trino \
+ --set catalog.metastore.uri=thrift://my-hms.example.internal:9083 \
+ --set catalog.filesystem.s3.existingSecret=my-s3-creds
+# or for AWS Glue + IAM-based S3 access:
+helm install hudi-trino hudi-lakehouse/charts/hudi-trino \
+ --set image.repository=my.registry/team/hudi-lakehouse-trino \
+ --set catalog.metastore.type=glue
+```
+
+`charts/hudi-trino/values-local-dev.yaml` is a fully worked example of the
+values surface. No binaries are ever committed: image builds stage locally
+built jars into gitignored `images/*/target/` directories.
+
+## Version compatibility notes
+
+- **Trino server is pinned to 472**: the `hudi-trino-plugin` performs a strict
+ SPI version match at load time. The chart deliberately has no Trino version
+ knob; it tracks the plugin.
+- **Table version pin**: the plugin currently reads with a Hudi 1.0.x runtime,
+ which understands table versions 6 and 8. Writers on this repository's
+ master default to a newer table version, so any table Trino must read has to
+ be written with `hoodie.write.table.version=8` and
+ `hoodie.write.auto.upgrade=false` (the local-dev example does this). This
+ pin goes away once the plugin's Hudi dependency is upgraded to a release
+ that reads the current table version.
+- **One Spark line**: the quickstart builds and runs Spark 3.5 / Scala 2.12
+ only (`apache/spark:3.5.x` ↔ `-Dspark3.5`), matching the pinned example
+ manifest. Everything runs dockerised, so there is no version matrix to
+ support here.
diff --git a/hudi-lakehouse/charts/hudi-agent-gateway/Chart.yaml b/hudi-lakehouse/charts/hudi-agent-gateway/Chart.yaml
new file mode 100644
index 000000000000..e38b44b4ec34
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-agent-gateway/Chart.yaml
@@ -0,0 +1,34 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+apiVersion: v2
+name: hudi-agent-gateway
+description: >-
+ The Apache Hudi agent gateway: a single service hosting the lakehouse agent
+ loop (chat API with sessions and SSE), an MCP server exposing guarded
+ lakehouse tools to external agents, and a chat UI. Deploy against an
+ existing Trino (hudi-trino chart) and your choice of LLM provider.
+type: application
+version: 0.1.0
+appVersion: "0.1.0"
+keywords:
+ - hudi
+ - ai
+ - mcp
+ - agent
+ - lakehouse
+home: https://hudi.apache.org
+sources:
+ - https://github.com/apache/hudi
diff --git a/hudi-lakehouse/charts/hudi-agent-gateway/templates/NOTES.txt b/hudi-lakehouse/charts/hudi-agent-gateway/templates/NOTES.txt
new file mode 100644
index 000000000000..1670610e5ec4
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-agent-gateway/templates/NOTES.txt
@@ -0,0 +1,46 @@
+{{- /*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/ -}}
+hudi-agent-gateway {{ .Chart.Version }} deployed.
+
+ provider : {{ .Values.gateway.provider }} ({{ .Values.gateway.model }})
+ trino : {{ .Values.trino.host }}:{{ .Values.trino.port }} (catalog {{ .Values.trino.catalog }})
+ mcp : {{ if .Values.mcpEnabled }}enabled at /mcp{{ else }}disabled{{ end }}
+
+Try it:
+ kubectl -n {{ .Release.Namespace }} port-forward svc/{{ include "hudi-agent-gateway.fullname" . }} 8000:{{ .Values.service.port }}
+
+ # chat UI
+ open http://localhost:8000/ui/
+
+ # agent chat API
+ curl -X POST localhost:8000/v1/chat -H 'Content-Type: application/json' \
+ -d '{"message": "How many trips per city?", "session_id": "s1"}'
+
+ # connect an MCP client (e.g. Claude Code)
+ claude mcp add --transport http hudi-lakehouse http://localhost:8000/mcp/
+
+{{- if and (eq .Values.gateway.provider "ollama") (contains "host.minikube.internal" .Values.gateway.ollama.baseUrl) }}
+
+NOTE: the gateway expects Ollama on the HOST machine. If it only binds
+loopback, restart it reachable from the cluster:
+ OLLAMA_HOST=0.0.0.0 ollama serve
+{{- end }}
+
+Readiness (kubectl -n {{ .Release.Namespace }} get pods) stays NotReady until
+both Trino and the LLM endpoint are reachable -- `curl localhost:8000/ready`
+shows per-dependency status.
diff --git a/hudi-lakehouse/charts/hudi-agent-gateway/templates/_helpers.tpl b/hudi-lakehouse/charts/hudi-agent-gateway/templates/_helpers.tpl
new file mode 100644
index 000000000000..43a1a7f2da94
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-agent-gateway/templates/_helpers.tpl
@@ -0,0 +1,52 @@
+{{- /*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/ -}}
+
+{{- define "hudi-agent-gateway.name" -}}
+{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
+{{- end -}}
+
+{{- define "hudi-agent-gateway.fullname" -}}
+{{- if .Values.fullnameOverride -}}
+{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
+{{- else -}}
+{{- printf "%s-%s" .Release.Name (include "hudi-agent-gateway.name" .) | trunc 63 | trimSuffix "-" -}}
+{{- end -}}
+{{- end -}}
+
+{{- define "hudi-agent-gateway.labels" -}}
+helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version }}
+app.kubernetes.io/name: {{ include "hudi-agent-gateway.name" . }}
+app.kubernetes.io/instance: {{ .Release.Name }}
+app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
+app.kubernetes.io/managed-by: {{ .Release.Service }}
+app.kubernetes.io/part-of: hudi-lakehouse
+{{- end -}}
+
+{{- define "hudi-agent-gateway.selectorLabels" -}}
+app.kubernetes.io/name: {{ include "hudi-agent-gateway.name" . }}
+app.kubernetes.io/instance: {{ .Release.Name }}
+{{- end -}}
+
+{{- /* Name of the Secret carrying LLM API keys, if any. */ -}}
+{{- define "hudi-agent-gateway.secretName" -}}
+{{- if .Values.gateway.existingSecret -}}
+{{- .Values.gateway.existingSecret -}}
+{{- else if or .Values.gateway.anthropicApiKey .Values.gateway.openaiApiKey -}}
+{{- printf "%s-llm" (include "hudi-agent-gateway.fullname" .) -}}
+{{- end -}}
+{{- end -}}
diff --git a/hudi-lakehouse/charts/hudi-agent-gateway/templates/deployment.yaml b/hudi-lakehouse/charts/hudi-agent-gateway/templates/deployment.yaml
new file mode 100644
index 000000000000..2258d2f5466e
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-agent-gateway/templates/deployment.yaml
@@ -0,0 +1,135 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+{{- $g := .Values.gateway }}
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: {{ include "hudi-agent-gateway.fullname" . }}
+ labels:
+ {{- include "hudi-agent-gateway.labels" . | nindent 4 }}
+spec:
+ # Sessions live in an in-memory checkpointer: run exactly one replica.
+ # (Horizontal scale requires the Postgres checkpointer; see the module README.)
+ replicas: 1
+ selector:
+ matchLabels:
+ {{- include "hudi-agent-gateway.selectorLabels" . | nindent 6 }}
+ template:
+ metadata:
+ labels:
+ {{- include "hudi-agent-gateway.selectorLabels" . | nindent 8 }}
+ spec:
+ securityContext:
+ runAsNonRoot: true
+ runAsUser: 1000
+ containers:
+ - name: gateway
+ image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
+ imagePullPolicy: {{ .Values.image.pullPolicy }}
+ ports:
+ - name: http
+ containerPort: 8000
+ {{- with include "hudi-agent-gateway.secretName" . }}
+ # Every key in the Secret becomes an env var; keys use standard
+ # provider names (ANTHROPIC_API_KEY, OPENAI_API_KEY, TOGETHER_API_KEY,
+ # ...), so new providers need no chart changes.
+ envFrom:
+ - secretRef:
+ name: {{ . }}
+ {{- end }}
+ env:
+ - name: GATEWAY_LLM_PROVIDER
+ value: {{ $g.provider | quote }}
+ - name: GATEWAY_LLM_MODEL
+ value: {{ $g.model | quote }}
+ - name: GATEWAY_LLM_TIMEOUT_SECONDS
+ value: {{ $g.llmTimeoutSeconds | quote }}
+ {{- with $g.ollama.baseUrl }}
+ - name: GATEWAY_OLLAMA_BASE_URL
+ value: {{ . | quote }}
+ {{- end }}
+ {{- with $g.openaiCompatible.baseUrl }}
+ - name: GATEWAY_OPENAI_BASE_URL
+ value: {{ . | quote }}
+ {{- end }}
+ {{- with $g.systemPromptExtra }}
+ - name: GATEWAY_SYSTEM_PROMPT_EXTRA
+ value: {{ . | quote }}
+ {{- end }}
+ - name: GATEWAY_TRINO_HOST
+ value: {{ .Values.trino.host | quote }}
+ - name: GATEWAY_TRINO_PORT
+ value: {{ .Values.trino.port | quote }}
+ - name: GATEWAY_TRINO_CATALOG
+ value: {{ .Values.trino.catalog | quote }}
+ - name: GATEWAY_TRINO_SCHEMA
+ value: {{ .Values.trino.schema | quote }}
+ - name: GATEWAY_TRINO_USER
+ value: {{ .Values.trino.user | quote }}
+ - name: GATEWAY_SQL_ROW_CAP
+ value: {{ .Values.guardrails.rowCap | quote }}
+ - name: GATEWAY_SQL_TIMEOUT_SECONDS
+ value: {{ .Values.guardrails.queryTimeoutSeconds | quote }}
+ - name: GATEWAY_TOOL_RESULT_MAX_BYTES
+ value: {{ .Values.guardrails.resultMaxBytes | quote }}
+ - name: GATEWAY_SESSION_TTL_SECONDS
+ value: {{ .Values.sessions.ttlSeconds | quote }}
+ - name: GATEWAY_MAX_SESSIONS
+ value: {{ .Values.sessions.maxSessions | quote }}
+ - name: GATEWAY_MAX_MESSAGES_PER_SESSION
+ value: {{ .Values.sessions.maxMessagesPerSession | quote }}
+ - name: GATEWAY_MCP_ENABLED
+ value: {{ .Values.mcpEnabled | quote }}
+ - name: GATEWAY_LOG_LEVEL
+ value: {{ .Values.logLevel | quote }}
+ {{- with .Values.extraEnv }}
+ {{- toYaml . | nindent 12 }}
+ {{- end }}
+ startupProbe:
+ httpGet:
+ path: /health
+ port: http
+ periodSeconds: 2
+ failureThreshold: 30
+ readinessProbe:
+ httpGet:
+ path: /ready
+ port: http
+ periodSeconds: 10
+ # /ready's own dependency checks budget up to ~8s (5s trino ping +
+ # 3s LLM probe) on a cache miss; the k8s default of 1s would flap.
+ timeoutSeconds: 9
+ failureThreshold: 3
+ livenessProbe:
+ httpGet:
+ path: /health
+ port: http
+ initialDelaySeconds: 10
+ periodSeconds: 20
+ resources:
+ {{- toYaml .Values.resources | nindent 12 }}
+ {{- with .Values.nodeSelector }}
+ nodeSelector:
+ {{- toYaml . | nindent 8 }}
+ {{- end }}
+ {{- with .Values.tolerations }}
+ tolerations:
+ {{- toYaml . | nindent 8 }}
+ {{- end }}
+ {{- with .Values.affinity }}
+ affinity:
+ {{- toYaml . | nindent 8 }}
+ {{- end }}
diff --git a/hudi-lakehouse/charts/hudi-agent-gateway/templates/secret.yaml b/hudi-lakehouse/charts/hudi-agent-gateway/templates/secret.yaml
new file mode 100644
index 000000000000..9cc5f1cbe103
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-agent-gateway/templates/secret.yaml
@@ -0,0 +1,35 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+{{- $g := .Values.gateway }}
+{{- if and (not $g.existingSecret) (or $g.anthropicApiKey $g.openaiApiKey) }}
+apiVersion: v1
+kind: Secret
+metadata:
+ name: {{ include "hudi-agent-gateway.fullname" . }}-llm
+ labels:
+ {{- include "hudi-agent-gateway.labels" . | nindent 4 }}
+type: Opaque
+# Keys are standard provider env-var names: the deployment mounts this Secret
+# via envFrom, so adding a future provider (TOGETHER_API_KEY, FIREWORKS_API_KEY,
+# BASETEN_API_KEY, HF_TOKEN, ...) requires no chart changes.
+stringData:
+ {{- with $g.anthropicApiKey }}
+ ANTHROPIC_API_KEY: {{ . | quote }}
+ {{- end }}
+ {{- with $g.openaiApiKey }}
+ OPENAI_API_KEY: {{ . | quote }}
+ {{- end }}
+{{- end }}
diff --git a/hudi-lakehouse/charts/hudi-agent-gateway/templates/service.yaml b/hudi-lakehouse/charts/hudi-agent-gateway/templates/service.yaml
new file mode 100644
index 000000000000..51d36deeacd1
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-agent-gateway/templates/service.yaml
@@ -0,0 +1,29 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+apiVersion: v1
+kind: Service
+metadata:
+ name: {{ include "hudi-agent-gateway.fullname" . }}
+ labels:
+ {{- include "hudi-agent-gateway.labels" . | nindent 4 }}
+spec:
+ type: {{ .Values.service.type }}
+ ports:
+ - name: http
+ port: {{ .Values.service.port }}
+ targetPort: http
+ selector:
+ {{- include "hudi-agent-gateway.selectorLabels" . | nindent 4 }}
diff --git a/hudi-lakehouse/charts/hudi-agent-gateway/values-local-dev.yaml b/hudi-lakehouse/charts/hudi-agent-gateway/values-local-dev.yaml
new file mode 100644
index 000000000000..143a24e4403c
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-agent-gateway/values-local-dev.yaml
@@ -0,0 +1,41 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Values used by local-dev/scripts/up.sh: the gateway talks to the in-cluster
+# Trino and to Ollama running on the developer's laptop. Switch to a hosted
+# provider with e.g.:
+# helm upgrade hudi-agent-gateway ... --set gateway.provider=anthropic \
+# --set gateway.anthropicApiKey=$ANTHROPIC_API_KEY
+fullnameOverride: hudi-agent-gateway
+
+gateway:
+ provider: ollama
+ # A small tool-capable model that fits a laptop; `ollama pull qwen3:4b`.
+ # (1.7b also works but makes more reasoning mistakes on SQL tasks.)
+ model: qwen3:4b
+ ollama:
+ baseUrl: http://host.minikube.internal:11434
+
+trino:
+ host: hudi-trino.hudi-lakehouse.svc.cluster.local
+ port: 8080
+
+resources:
+ requests:
+ cpu: 100m
+ memory: 256Mi
+ limits:
+ memory: 512Mi
diff --git a/hudi-lakehouse/charts/hudi-agent-gateway/values.yaml b/hudi-lakehouse/charts/hudi-agent-gateway/values.yaml
new file mode 100644
index 000000000000..e8880ba9ab60
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-agent-gateway/values.yaml
@@ -0,0 +1,94 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Default values for the hudi-agent-gateway chart.
+#
+# The gateway points at an existing Trino with the Hudi connector (see the
+# sibling hudi-trino chart) and at the LLM provider of your choice. For the
+# self-contained laptop environment see hudi-lakehouse/local-dev/.
+
+nameOverride: ""
+fullnameOverride: ""
+
+image:
+ # Built by hudi-lakehouse/scripts/build-images.sh from hudi-agent-gateway/.
+ repository: hudi-lakehouse-agent-gateway
+ tag: "0.1.0"
+ pullPolicy: IfNotPresent
+
+gateway:
+ # anthropic | openai | ollama | openai-compatible
+ provider: ollama
+ model: qwen3:8b
+ # Appended to the built-in system prompt.
+ systemPromptExtra: ""
+ # Inline API keys are for development only -- they land in a chart-managed
+ # Secret. For real deployments create a Secret yourself and set
+ # existingSecret. The Secret is mounted with envFrom, and its keys must be
+ # the providers' STANDARD env-var names (ANTHROPIC_API_KEY, OPENAI_API_KEY;
+ # future providers -- TOGETHER_API_KEY, FIREWORKS_API_KEY, BASETEN_API_KEY,
+ # HF_TOKEN, ... -- work with no chart changes). Compatible with External
+ # Secrets Operator / Vault CSI: point existingSecret at the materialized
+ # Secret.
+ anthropicApiKey: ""
+ openaiApiKey: ""
+ existingSecret: ""
+ ollama:
+ # e.g. http://host.minikube.internal:11434 for Ollama on the laptop, or
+ # an in-cluster Ollama/vLLM service.
+ baseUrl: ""
+ openaiCompatible:
+ # Endpoint for provider=openai-compatible (vLLM, Together, Fireworks, ...).
+ baseUrl: ""
+ llmTimeoutSeconds: 120
+
+trino:
+ host: hudi-trino.hudi-lakehouse.svc
+ port: 8080
+ catalog: hudi
+ schema: default
+ user: hudi-agent-gateway
+
+guardrails:
+ rowCap: 200
+ queryTimeoutSeconds: 120
+ resultMaxBytes: 50000
+
+sessions:
+ ttlSeconds: 3600
+ maxSessions: 1000
+ maxMessagesPerSession: 40
+
+mcpEnabled: true
+logLevel: INFO
+
+service:
+ type: ClusterIP
+ port: 8000
+
+resources:
+ requests:
+ cpu: 250m
+ memory: 512Mi
+ limits:
+ memory: 1Gi
+
+# Extra environment variables for the gateway container.
+extraEnv: []
+
+nodeSelector: {}
+tolerations: []
+affinity: {}
diff --git a/hudi-lakehouse/charts/hudi-trino/.helmignore b/hudi-lakehouse/charts/hudi-trino/.helmignore
new file mode 100644
index 000000000000..59cab213f155
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-trino/.helmignore
@@ -0,0 +1,24 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Patterns to ignore when building helm packages.
+.DS_Store
+.git/
+.gitignore
+*.swp
+*.bak
+*.tmp
+*.orig
\ No newline at end of file
diff --git a/hudi-lakehouse/charts/hudi-trino/Chart.yaml b/hudi-lakehouse/charts/hudi-trino/Chart.yaml
new file mode 100644
index 000000000000..5ab52256797f
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-trino/Chart.yaml
@@ -0,0 +1,32 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+apiVersion: v2
+name: hudi-trino
+description: >-
+ Trino query engine with the Apache Hudi connector built from the Hudi
+ repository. Deploy against an existing Hive Metastore (or AWS Glue) and
+ object storage to serve SQL over Hudi tables.
+type: application
+version: 0.1.0
+# The Trino server version is pinned by the plugin's strict SPI version check.
+appVersion: "472"
+keywords:
+ - hudi
+ - trino
+ - lakehouse
+home: https://hudi.apache.org
+sources:
+ - https://github.com/apache/hudi
diff --git a/hudi-lakehouse/charts/hudi-trino/templates/NOTES.txt b/hudi-lakehouse/charts/hudi-trino/templates/NOTES.txt
new file mode 100644
index 000000000000..00bcbf84bc74
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-trino/templates/NOTES.txt
@@ -0,0 +1,32 @@
+{{- /*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/ -}}
+hudi-trino {{ .Chart.Version }} deployed (Trino {{ .Chart.AppVersion }} + Hudi connector).
+
+Catalog "{{ .Values.catalog.name }}" points at:
+ metastore : {{ .Values.catalog.metastore.type }}{{ if eq .Values.catalog.metastore.type "thrift" }} ({{ .Values.catalog.metastore.uri }}){{ end }}
+ s3 : {{ if .Values.catalog.filesystem.s3.enabled }}enabled{{ with .Values.catalog.filesystem.s3.endpoint }} ({{ . }}){{ end }}{{ else }}disabled{{ end }}
+
+Try it:
+ kubectl -n {{ .Release.Namespace }} port-forward svc/{{ include "hudi-trino.fullname" . }} 8080:{{ .Values.service.port }}
+ # Web UI: http://localhost:8080 (any username)
+
+ kubectl -n {{ .Release.Namespace }} exec deploy/{{ include "hudi-trino.fullname" . }} -- \
+ trino --execute 'SHOW CATALOGS'
+
+ kubectl -n {{ .Release.Namespace }} exec deploy/{{ include "hudi-trino.fullname" . }} -- \
+ trino --execute 'SHOW TABLES FROM {{ .Values.catalog.name }}.default'
diff --git a/hudi-lakehouse/charts/hudi-trino/templates/_helpers.tpl b/hudi-lakehouse/charts/hudi-trino/templates/_helpers.tpl
new file mode 100644
index 000000000000..f7d5d3f7a042
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-trino/templates/_helpers.tpl
@@ -0,0 +1,52 @@
+{{- /*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/ -}}
+
+{{- define "hudi-trino.name" -}}
+{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
+{{- end -}}
+
+{{- define "hudi-trino.fullname" -}}
+{{- if .Values.fullnameOverride -}}
+{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
+{{- else -}}
+{{- printf "%s-%s" .Release.Name (include "hudi-trino.name" .) | trunc 63 | trimSuffix "-" -}}
+{{- end -}}
+{{- end -}}
+
+{{- define "hudi-trino.labels" -}}
+helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version }}
+app.kubernetes.io/name: {{ include "hudi-trino.name" . }}
+app.kubernetes.io/instance: {{ .Release.Name }}
+app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
+app.kubernetes.io/managed-by: {{ .Release.Service }}
+app.kubernetes.io/part-of: hudi-lakehouse
+{{- end -}}
+
+{{- define "hudi-trino.selectorLabels" -}}
+app.kubernetes.io/name: {{ include "hudi-trino.name" . }}
+app.kubernetes.io/instance: {{ .Release.Name }}
+{{- end -}}
+
+{{- /* Name of the Secret carrying S3 credentials, if any. */ -}}
+{{- define "hudi-trino.s3SecretName" -}}
+{{- if .Values.catalog.filesystem.s3.existingSecret -}}
+{{- .Values.catalog.filesystem.s3.existingSecret -}}
+{{- else if and .Values.catalog.filesystem.s3.accessKey .Values.catalog.filesystem.s3.secretKey -}}
+{{- printf "%s-s3" (include "hudi-trino.fullname" .) -}}
+{{- end -}}
+{{- end -}}
diff --git a/hudi-lakehouse/charts/hudi-trino/templates/configmap-catalog.yaml b/hudi-lakehouse/charts/hudi-trino/templates/configmap-catalog.yaml
new file mode 100644
index 000000000000..246a0d25ba57
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-trino/templates/configmap-catalog.yaml
@@ -0,0 +1,58 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+{{- $s3 := .Values.catalog.filesystem.s3 }}
+apiVersion: v1
+kind: ConfigMap
+metadata:
+ name: {{ include "hudi-trino.fullname" . }}-catalog
+ labels:
+ {{- include "hudi-trino.labels" . | nindent 4 }}
+data:
+ {{ .Values.catalog.name }}.properties: |
+ connector.name=hudi
+ {{- if eq .Values.catalog.metastore.type "thrift" }}
+ {{- if not .Values.catalog.metastore.uri }}
+ {{- fail "catalog.metastore.uri is required when catalog.metastore.type=thrift" }}
+ {{- end }}
+ hive.metastore.uri={{ .Values.catalog.metastore.uri }}
+ {{- else if eq .Values.catalog.metastore.type "glue" }}
+ hive.metastore=glue
+ {{- range $k, $v := .Values.catalog.metastore.glueProperties }}
+ {{ $k }}={{ $v }}
+ {{- end }}
+ {{- else }}
+ {{- fail (printf "unsupported catalog.metastore.type %q (thrift|glue)" .Values.catalog.metastore.type) }}
+ {{- end }}
+ {{- if $s3.enabled }}
+ fs.native-s3.enabled=true
+ {{- if $s3.endpoint }}
+ s3.endpoint={{ $s3.endpoint }}
+ {{- end }}
+ s3.region={{ $s3.region }}
+ s3.path-style-access={{ $s3.pathStyleAccess }}
+ {{- if include "hudi-trino.s3SecretName" . }}
+ # Credentials come from the environment (Secret-backed); see deployment.yaml.
+ s3.aws-access-key=${ENV:HUDI_TRINO_S3_ACCESS_KEY}
+ s3.aws-secret-key=${ENV:HUDI_TRINO_S3_SECRET_KEY}
+ {{- end }}
+ {{- end }}
+ {{- range $k, $v := .Values.catalog.extraProperties }}
+ {{ $k }}={{ $v }}
+ {{- end }}
+ {{- if .Values.catalog.tpchEnabled }}
+ tpch.properties: |
+ connector.name=tpch
+ {{- end }}
diff --git a/hudi-lakehouse/charts/hudi-trino/templates/deployment.yaml b/hudi-lakehouse/charts/hudi-trino/templates/deployment.yaml
new file mode 100644
index 000000000000..dd9e30211210
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-trino/templates/deployment.yaml
@@ -0,0 +1,90 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: {{ include "hudi-trino.fullname" . }}
+ labels:
+ {{- include "hudi-trino.labels" . | nindent 4 }}
+spec:
+ replicas: 1
+ selector:
+ matchLabels:
+ {{- include "hudi-trino.selectorLabels" . | nindent 6 }}
+ template:
+ metadata:
+ labels:
+ {{- include "hudi-trino.selectorLabels" . | nindent 8 }}
+ annotations:
+ # Roll the pod when the catalog config changes.
+ checksum/catalog: {{ include (print $.Template.BasePath "/configmap-catalog.yaml") . | sha256sum }}
+ spec:
+ containers:
+ - name: trino
+ image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
+ imagePullPolicy: {{ .Values.image.pullPolicy }}
+ ports:
+ - name: http
+ containerPort: 8080
+ env:
+ {{- with include "hudi-trino.s3SecretName" . }}
+ - name: HUDI_TRINO_S3_ACCESS_KEY
+ valueFrom:
+ secretKeyRef:
+ name: {{ . }}
+ key: accessKey
+ - name: HUDI_TRINO_S3_SECRET_KEY
+ valueFrom:
+ secretKeyRef:
+ name: {{ . }}
+ key: secretKey
+ {{- end }}
+ {{- with .Values.extraEnv }}
+ {{- toYaml . | nindent 12 }}
+ {{- end }}
+ volumeMounts:
+ - name: catalog
+ mountPath: /etc/trino/catalog
+ readinessProbe:
+ httpGet:
+ path: /v1/info
+ port: http
+ initialDelaySeconds: 20
+ periodSeconds: 10
+ livenessProbe:
+ httpGet:
+ path: /v1/info
+ port: http
+ initialDelaySeconds: 60
+ periodSeconds: 20
+ resources:
+ {{- toYaml .Values.resources | nindent 12 }}
+ volumes:
+ - name: catalog
+ configMap:
+ name: {{ include "hudi-trino.fullname" . }}-catalog
+ {{- with .Values.nodeSelector }}
+ nodeSelector:
+ {{- toYaml . | nindent 8 }}
+ {{- end }}
+ {{- with .Values.tolerations }}
+ tolerations:
+ {{- toYaml . | nindent 8 }}
+ {{- end }}
+ {{- with .Values.affinity }}
+ affinity:
+ {{- toYaml . | nindent 8 }}
+ {{- end }}
diff --git a/hudi-lakehouse/charts/hudi-trino/templates/secret.yaml b/hudi-lakehouse/charts/hudi-trino/templates/secret.yaml
new file mode 100644
index 000000000000..d9fc1f09e9e4
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-trino/templates/secret.yaml
@@ -0,0 +1,28 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+{{- $s3 := .Values.catalog.filesystem.s3 }}
+{{- if and $s3.enabled (not $s3.existingSecret) $s3.accessKey $s3.secretKey }}
+apiVersion: v1
+kind: Secret
+metadata:
+ name: {{ include "hudi-trino.fullname" . }}-s3
+ labels:
+ {{- include "hudi-trino.labels" . | nindent 4 }}
+type: Opaque
+stringData:
+ accessKey: {{ $s3.accessKey | quote }}
+ secretKey: {{ $s3.secretKey | quote }}
+{{- end }}
diff --git a/hudi-lakehouse/charts/hudi-trino/templates/service.yaml b/hudi-lakehouse/charts/hudi-trino/templates/service.yaml
new file mode 100644
index 000000000000..0257bbbd79b1
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-trino/templates/service.yaml
@@ -0,0 +1,29 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+apiVersion: v1
+kind: Service
+metadata:
+ name: {{ include "hudi-trino.fullname" . }}
+ labels:
+ {{- include "hudi-trino.labels" . | nindent 4 }}
+spec:
+ type: {{ .Values.service.type }}
+ ports:
+ - name: http
+ port: {{ .Values.service.port }}
+ targetPort: http
+ selector:
+ {{- include "hudi-trino.selectorLabels" . | nindent 4 }}
diff --git a/hudi-lakehouse/charts/hudi-trino/values-local-dev.yaml b/hudi-lakehouse/charts/hudi-trino/values-local-dev.yaml
new file mode 100644
index 000000000000..fa9471c6683b
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-trino/values-local-dev.yaml
@@ -0,0 +1,41 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Values used by local-dev/scripts/up.sh to point the hudi-trino chart at the
+# in-cluster MinIO + Hive Metastore that local-dev stands up. Also serves as a
+# worked example of configuring the chart against custom infrastructure.
+fullnameOverride: hudi-trino
+
+catalog:
+ metastore:
+ type: thrift
+ uri: thrift://hive-metastore.hudi-lakehouse.svc.cluster.local:9083
+ filesystem:
+ s3:
+ enabled: true
+ endpoint: http://minio.hudi-lakehouse.svc.cluster.local:9000
+ region: us-east-1
+ pathStyleAccess: true
+ # Fixed local-dev credentials (see local-dev/manifests/minio.yaml).
+ accessKey: admin
+ secretKey: password
+
+resources:
+ requests:
+ cpu: 500m
+ memory: 2Gi
+ limits:
+ memory: 4Gi
diff --git a/hudi-lakehouse/charts/hudi-trino/values.yaml b/hudi-lakehouse/charts/hudi-trino/values.yaml
new file mode 100644
index 000000000000..6522def5f12b
--- /dev/null
+++ b/hudi-lakehouse/charts/hudi-trino/values.yaml
@@ -0,0 +1,83 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Default values for the hudi-trino chart.
+#
+# This chart deploys ONLY Trino (with the Hudi connector built from this
+# repository). It expects the catalog (Hive Metastore or AWS Glue) and the
+# object storage to already exist -- point the values below at them. For a
+# self-contained laptop environment that stands those up too, see
+# hudi-lakehouse/local-dev/.
+
+nameOverride: ""
+fullnameOverride: ""
+
+image:
+ # Built by hudi-lakehouse/scripts/build-images.sh. For real clusters,
+ # push to a registry and override the repository.
+ repository: hudi-lakehouse-trino
+ # The tag tracks the pinned Trino server version (strict SPI match).
+ tag: "472"
+ pullPolicy: IfNotPresent
+
+catalog:
+ # Name of the Trino catalog exposing Hudi tables (i.e. `SELECT .. FROM <name>.<db>.<table>`).
+ name: hudi
+ metastore:
+ # thrift | glue
+ type: thrift
+ # Required when type=thrift, e.g. thrift://hive-metastore.default.svc:9083
+ uri: ""
+ # Optional extra properties for glue (region etc.), rendered verbatim.
+ glueProperties: {}
+ filesystem:
+ s3:
+ enabled: true
+ # Leave endpoint empty for real AWS S3; set for MinIO/other S3-compatible stores.
+ endpoint: ""
+ region: us-east-1
+ pathStyleAccess: false
+ # Static credentials are injected via a Secret and referenced from the
+ # catalog file through environment substitution -- they never appear in
+ # the ConfigMap. Leave both empty to use the pod's IAM identity (IRSA etc.).
+ accessKey: ""
+ secretKey: ""
+ # Name of an existing Secret with keys `accessKey` and `secretKey`;
+ # takes precedence over the inline values above.
+ existingSecret: ""
+ # Extra key=value pairs appended verbatim to the Hudi catalog properties.
+ extraProperties: {}
+ # Include the tpch catalog for connectivity sanity checks (SELECT 1 etc.).
+ tpchEnabled: true
+
+service:
+ type: ClusterIP
+ port: 8080
+
+resources:
+ requests:
+ cpu: "1"
+ memory: 4Gi
+ limits:
+ memory: 6Gi
+
+# Extra environment variables for the Trino container (e.g. to surface
+# additional secrets for ${ENV:...} substitution in extraProperties).
+extraEnv: []
+
+nodeSelector: {}
+tolerations: []
+affinity: {}
diff --git a/hudi-lakehouse/charts/vllm/Chart.yaml b/hudi-lakehouse/charts/vllm/Chart.yaml
new file mode 100644
index 000000000000..babea1349532
--- /dev/null
+++ b/hudi-lakehouse/charts/vllm/Chart.yaml
@@ -0,0 +1,32 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+apiVersion: v2
+name: vllm
+description: >-
+ vLLM serving one open-weight model behind an OpenAI-compatible API, for use
+ as the hudi-agent-gateway's in-cluster LLM (gateway provider
+ "openai-compatible"). Requires a GPU node.
+type: application
+version: 0.1.0
+appVersion: "v0.25.0"
+keywords:
+ - vllm
+ - llm
+ - inference
+ - lakehouse
+home: https://hudi.apache.org
+sources:
+ - https://github.com/apache/hudi
diff --git a/hudi-lakehouse/charts/vllm/templates/NOTES.txt b/hudi-lakehouse/charts/vllm/templates/NOTES.txt
new file mode 100644
index 000000000000..984e17393224
--- /dev/null
+++ b/hudi-lakehouse/charts/vllm/templates/NOTES.txt
@@ -0,0 +1,32 @@
+{{- /*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/ -}}
+vllm {{ .Chart.Version }} deployed, serving {{ .Values.model }}.
+
+First boot downloads the model weights -- expect several minutes before the
+pod is Ready (watch: kubectl -n {{ .Release.Namespace }} get pods -w).
+
+Point the hudi-agent-gateway at it:
+
+ helm upgrade hudi-agent-gateway <chart> --reuse-values \
+ --set gateway.provider=openai-compatible \
+ --set gateway.openaiCompatible.baseUrl=http://{{ include "vllm.fullname" . }}.{{ .Release.Namespace }}.svc:{{ .Values.service.port }}/v1 \
+ --set gateway.model={{ .Values.model }}
+
+Sanity check:
+ kubectl -n {{ .Release.Namespace }} port-forward svc/{{ include "vllm.fullname" . }} 8001:{{ .Values.service.port }}
+ curl localhost:8001/v1/models
diff --git a/hudi-lakehouse/charts/vllm/templates/_helpers.tpl b/hudi-lakehouse/charts/vllm/templates/_helpers.tpl
new file mode 100644
index 000000000000..3812040072c6
--- /dev/null
+++ b/hudi-lakehouse/charts/vllm/templates/_helpers.tpl
@@ -0,0 +1,43 @@
+{{- /*
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+*/ -}}
+
+{{- define "vllm.name" -}}
+{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" -}}
+{{- end -}}
+
+{{- define "vllm.fullname" -}}
+{{- if .Values.fullnameOverride -}}
+{{- .Values.fullnameOverride | trunc 63 | trimSuffix "-" -}}
+{{- else -}}
+{{- printf "%s-%s" .Release.Name (include "vllm.name" .) | trunc 63 | trimSuffix "-" -}}
+{{- end -}}
+{{- end -}}
+
+{{- define "vllm.labels" -}}
+helm.sh/chart: {{ printf "%s-%s" .Chart.Name .Chart.Version }}
+app.kubernetes.io/name: {{ include "vllm.name" . }}
+app.kubernetes.io/instance: {{ .Release.Name }}
+app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
+app.kubernetes.io/managed-by: {{ .Release.Service }}
+app.kubernetes.io/part-of: hudi-lakehouse
+{{- end -}}
+
+{{- define "vllm.selectorLabels" -}}
+app.kubernetes.io/name: {{ include "vllm.name" . }}
+app.kubernetes.io/instance: {{ .Release.Name }}
+{{- end -}}
diff --git a/hudi-lakehouse/charts/vllm/templates/deployment.yaml b/hudi-lakehouse/charts/vllm/templates/deployment.yaml
new file mode 100644
index 000000000000..785643ec94de
--- /dev/null
+++ b/hudi-lakehouse/charts/vllm/templates/deployment.yaml
@@ -0,0 +1,102 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: {{ include "vllm.fullname" . }}
+ labels:
+ {{- include "vllm.labels" . | nindent 4 }}
+spec:
+ replicas: 1
+ # Model load pins the GPU; never run old and new pods concurrently.
+ strategy:
+ type: Recreate
+ selector:
+ matchLabels:
+ {{- include "vllm.selectorLabels" . | nindent 6 }}
+ template:
+ metadata:
+ labels:
+ {{- include "vllm.selectorLabels" . | nindent 8 }}
+ spec:
+ containers:
+ - name: vllm
+ image: "{{ .Values.image.repository }}:{{ .Values.image.tag }}"
+ imagePullPolicy: {{ .Values.image.pullPolicy }}
+ args:
+ - --model
+ - {{ .Values.model | quote }}
+ - --port
+ - "8000"
+ {{- range .Values.extraArgs }}
+ - {{ . | quote }}
+ {{- end }}
+ {{- with .Values.existingSecret }}
+ envFrom:
+ - secretRef:
+ name: {{ . }}
+ {{- end }}
+ ports:
+ - name: http
+ containerPort: 8000
+ startupProbe:
+ httpGet:
+ path: /health
+ port: http
+ periodSeconds: {{ .Values.startupProbe.periodSeconds }}
+ failureThreshold: {{ .Values.startupProbe.failureThreshold }}
+ readinessProbe:
+ httpGet:
+ path: /health
+ port: http
+ periodSeconds: 10
+ livenessProbe:
+ httpGet:
+ path: /health
+ port: http
+ periodSeconds: 30
+ volumeMounts:
+ - name: model-cache
+ mountPath: /root/.cache/huggingface
+ - name: shm
+ mountPath: /dev/shm
+ resources:
+ {{- toYaml .Values.resources | nindent 12 }}
+ volumes:
+ - name: model-cache
+ {{- if .Values.persistence.enabled }}
+ persistentVolumeClaim:
+ claimName: {{ include "vllm.fullname" . }}-cache
+ {{- else }}
+ emptyDir: {}
+ {{- end }}
+ # PyTorch tensor-parallel workers need generous shared memory.
+ - name: shm
+ emptyDir:
+ medium: Memory
+ sizeLimit: 8Gi
+ {{- with .Values.nodeSelector }}
+ nodeSelector:
+ {{- toYaml . | nindent 8 }}
+ {{- end }}
+ {{- with .Values.tolerations }}
+ tolerations:
+ {{- toYaml . | nindent 8 }}
+ {{- end }}
+ {{- with .Values.affinity }}
+ affinity:
+ {{- toYaml . | nindent 8 }}
+ {{- end }}
diff --git a/hudi-lakehouse/charts/vllm/templates/pvc.yaml b/hudi-lakehouse/charts/vllm/templates/pvc.yaml
new file mode 100644
index 000000000000..fb09f236fbcc
--- /dev/null
+++ b/hudi-lakehouse/charts/vllm/templates/pvc.yaml
@@ -0,0 +1,31 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+{{- if .Values.persistence.enabled }}
+apiVersion: v1
+kind: PersistentVolumeClaim
+metadata:
+ name: {{ include "vllm.fullname" . }}-cache
+ labels:
+ {{- include "vllm.labels" . | nindent 4 }}
+spec:
+ accessModes: ["ReadWriteOnce"]
+ resources:
+ requests:
+ storage: {{ .Values.persistence.size }}
+ {{- with .Values.persistence.storageClass }}
+ storageClassName: {{ . }}
+ {{- end }}
+{{- end }}
diff --git a/hudi-lakehouse/charts/vllm/templates/service.yaml b/hudi-lakehouse/charts/vllm/templates/service.yaml
new file mode 100644
index 000000000000..c46564aae51f
--- /dev/null
+++ b/hudi-lakehouse/charts/vllm/templates/service.yaml
@@ -0,0 +1,29 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+apiVersion: v1
+kind: Service
+metadata:
+ name: {{ include "vllm.fullname" . }}
+ labels:
+ {{- include "vllm.labels" . | nindent 4 }}
+spec:
+ type: {{ .Values.service.type }}
+ ports:
+ - name: http
+ port: {{ .Values.service.port }}
+ targetPort: http
+ selector:
+ {{- include "vllm.selectorLabels" . | nindent 4 }}
diff --git a/hudi-lakehouse/charts/vllm/values.yaml b/hudi-lakehouse/charts/vllm/values.yaml
new file mode 100644
index 000000000000..84253952bf93
--- /dev/null
+++ b/hudi-lakehouse/charts/vllm/values.yaml
@@ -0,0 +1,86 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Default values for the vllm chart.
+#
+# One vLLM server, one model, chosen at install time. OPTIONAL and GPU-only:
+# the out-of-box gateway experience uses Ollama; install this chart when you
+# want a bigger open-weight model served in-cluster, then point the
+# hudi-agent-gateway at it:
+#
+# helm install vllm hudi-lakehouse/charts/vllm --set model=Qwen/Qwen3-8B
+# helm upgrade hudi-agent-gateway ... \
+# --set gateway.provider=openai-compatible \
+# --set gateway.openaiCompatible.baseUrl=http://vllm:8000/v1 \
+# --set gateway.model=Qwen/Qwen3-8B
+
+nameOverride: ""
+fullnameOverride: ""
+
+image:
+ repository: vllm/vllm-openai
+ tag: "v0.25.0-ubuntu2404"
+ pullPolicy: IfNotPresent
+
+# The Hugging Face model to serve. UNGATED defaults work with no token:
+# Qwen/Qwen3-8B (default; Apache-2.0, tool calling)
+# Qwen/Qwen3-32B (bigger; needs ~2x A100-40GB or 1x A100-80GB)
+# openai/gpt-oss-20b (Apache-2.0)
+# GATED models (meta-llama/*, mistralai/*, google/gemma*) additionally need
+# an HF_TOKEN key in the secret referenced below.
+model: Qwen/Qwen3-8B
+
+# Extra CLI args appended to the vLLM server (e.g. --max-model-len 16384,
+# --tensor-parallel-size 2, --enable-auto-tool-choice --tool-call-parser hermes).
+extraArgs:
+ # Tool calling is required by the hudi-agent-gateway agent loop; hermes is the
+ # right parser for Qwen models -- adjust when changing model families.
+ - --enable-auto-tool-choice
+ - --tool-call-parser
+ - hermes
+
+# Secret with standard env-var keys (HF_TOKEN for gated models). Same
+# convention as the hudi-agent-gateway chart: mounted via envFrom.
+existingSecret: ""
+
+# Model weights cache; strongly recommended so pod restarts don't re-download.
+persistence:
+ enabled: true
+ size: 60Gi
+ storageClass: ""
+
+resources:
+ requests:
+ cpu: "4"
+ memory: 24Gi
+ nvidia.com/gpu: 1
+ limits:
+ memory: 32Gi
+ nvidia.com/gpu: 1
+
+service:
+ type: ClusterIP
+ port: 8000
+
+# vLLM startup (download + load + CUDA graph capture) can take many minutes
+# on first boot; the startup probe budget covers it.
+startupProbe:
+ failureThreshold: 120
+ periodSeconds: 10
+
+nodeSelector: {}
+tolerations: []
+affinity: {}
diff --git a/hudi-lakehouse/images/spark/Dockerfile b/hudi-lakehouse/images/spark/Dockerfile
new file mode 100644
index 000000000000..4c082b189b6c
--- /dev/null
+++ b/hudi-lakehouse/images/spark/Dockerfile
@@ -0,0 +1,42 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Spark runtime with the Hudi Spark bundle built from this repository, used by
+# the local-dev environment to run Hudi write jobs on Kubernetes.
+#
+# Build context: this directory. scripts/build-images.sh stages the bundle jar
+# (packaging/hudi-spark-bundle/target/hudi-spark*-bundle_*.jar) into ./target/
+# first; the staging directory is gitignored so jars never enter version
+# control.
+#
+# The Scala version of the base image must match the bundle:
+# apache/spark:3.5.x (Scala 2.12) <-> hudi-spark3.5-bundle_2.12
+# apache/spark:4.1.x (Scala 2.13) <-> hudi-spark4.1-bundle_2.13
+ARG SPARK_IMAGE_TAG=3.5.7-scala2.12-java17-python3-ubuntu
+FROM apache/spark:${SPARK_IMAGE_TAG}
+
+ARG HADOOP_AWS_VERSION=3.3.4
+ARG AWS_SDK_VERSION=1.12.772
+ARG HUDI_SPARK_BUNDLE_JAR
+
+USER root
+RUN set -eux; \
+ wget -q -O /opt/spark/jars/hadoop-aws-${HADOOP_AWS_VERSION}.jar \
+ https://repo1.maven.org/maven2/org/apache/hadoop/hadoop-aws/${HADOOP_AWS_VERSION}/hadoop-aws-${HADOOP_AWS_VERSION}.jar; \
+ wget -q -O /opt/spark/jars/aws-java-sdk-bundle-${AWS_SDK_VERSION}.jar \
+ https://repo1.maven.org/maven2/com/amazonaws/aws-java-sdk-bundle/${AWS_SDK_VERSION}/aws-java-sdk-bundle-${AWS_SDK_VERSION}.jar
+COPY target/${HUDI_SPARK_BUNDLE_JAR} /opt/spark/jars/
+USER spark
diff --git a/hudi-lakehouse/images/trino/Dockerfile b/hudi-lakehouse/images/trino/Dockerfile
new file mode 100644
index 000000000000..a9931a9dda3b
--- /dev/null
+++ b/hudi-lakehouse/images/trino/Dockerfile
@@ -0,0 +1,33 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Trino server with the Hudi connector built from this repository.
+#
+# Build context: this directory. scripts/build-images.sh stages the exploded
+# plugin (hudi-trino-plugin/target/trino-hudi-472/) into ./target/ first; the
+# staging directory is gitignored so plugin jars never enter version control.
+#
+# The Trino server version is pinned to 472 because the plugin performs a
+# strict SPI version match at load time (see HudiConnectorFactory).
+FROM trinodb/trino:472
+
+USER root
+# Replace the hudi plugin bundled with the upstream image with the one built
+# from this repository.
+RUN rm -rf /usr/lib/trino/plugin/hudi
+COPY target/trino-hudi-472/ /usr/lib/trino/plugin/hudi/
+RUN chown -R trino:trino /usr/lib/trino/plugin/hudi
+USER trino
diff --git a/hudi-lakehouse/local-dev/README.md b/hudi-lakehouse/local-dev/README.md
new file mode 100644
index 000000000000..1e52dc2b708c
--- /dev/null
+++ b/hudi-lakehouse/local-dev/README.md
@@ -0,0 +1,71 @@
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+# local-dev: a laptop Hudi lakehouse
+
+This directory stands up a complete, self-contained Hudi lakehouse on a local
+Kubernetes cluster (minikube) for **development only**:
+
+| Piece | What | Why it's here and not in a chart |
+|---|---|---|
+| `manifests/minio.yaml` | S3-compatible object storage (fixed creds `admin`/`password`) | in real deployments you bring your own S3/GCS |
+| `manifests/hive-metastore.yaml` | Derby-backed HMS on thrift 9083 | in real deployments you bring your own HMS/Glue |
+| Apache Spark Kubernetes Operator | runs `SparkApplication` jobs | installed from its upstream helm chart by `up.sh` |
+| `charts/hudi-trino` (product chart) | Trino + the Hudi connector | the same chart used against real infrastructure, installed with `values-local-dev.yaml` |
+| `example/` | copy-me template to submit any Spark job | see its README |
+
+## Quickstart
+
+```bash
+# 1. build jars + images (from the repo root)
+./hudi-lakehouse/scripts/build-jars.sh # spark bundle (JDK 11/17) + trino plugin (JDK 23)
+minikube start --cpus 4 --memory 10g
+eval "$(minikube docker-env)"
+./hudi-lakehouse/scripts/build-images.sh
+
+# 2. bring up the stack
+./hudi-lakehouse/local-dev/scripts/up.sh
+
+# 3. write a Hudi table (Spark) + register it in HMS
+./hudi-lakehouse/local-dev/scripts/run-example.sh
+
+# 4. query it from Trino
+kubectl -n hudi-lakehouse exec deploy/hudi-trino -- \
+ trino --execute "SELECT city, count(*) FROM hudi.default.trips GROUP BY city"
+
+# or run 2-4 plus assertions in one shot:
+./hudi-lakehouse/local-dev/scripts/smoke-test.sh
+
+# tear down
+./hudi-lakehouse/local-dev/scripts/down.sh
+```
+
+Consoles (via `kubectl -n hudi-lakehouse port-forward`):
+MinIO `svc/minio 9001`, Trino UI `svc/hudi-trino 8080`.
+
+## Optional: vLLM instead of Ollama
+
+If your cluster has a GPU node, `INSTALL_VLLM=1 ./scripts/up.sh` also installs
+the `vllm` chart (default model `Qwen/Qwen3-8B`, override with `VLLM_MODEL=`)
+and points the gateway at it instead of host Ollama.
+
+## Notes
+
+- `apache/hive:3.1.3` is amd64-only; on Apple-silicon minikube it runs under
+ emulation (slower HMS startup, functionally fine).
+- Tables that Trino must read are written with `hoodie.write.table.version=8`
+ and `hoodie.write.auto.upgrade=false` — see the note in the top-level README.
diff --git a/hudi-lakehouse/local-dev/example/README.md b/hudi-lakehouse/local-dev/example/README.md
new file mode 100644
index 000000000000..315f0c29a04d
--- /dev/null
+++ b/hudi-lakehouse/local-dev/example/README.md
@@ -0,0 +1,55 @@
+<!--
+Licensed to the Apache Software Foundation (ASF) under one
+or more contributor license agreements. See the NOTICE file
+distributed with this work for additional information
+regarding copyright ownership. The ASF licenses this file
+to you under the Apache License, Version 2.0 (the
+"License"); you may not use this file except in compliance
+with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+# Example: submitting a Hudi Spark job
+
+This folder is a **copy-me template** for running Spark jobs against the
+local-dev lakehouse (and, with adjusted endpoints, any cluster):
+
+- `hudi_table_writer.py` — a PySpark job that writes a partitioned Hudi
+ Copy-on-Write table to object storage and registers it in the Hive
+ Metastore via hive-sync, making it queryable from Trino.
+- `spark-app.yaml` — the `SparkApplication` resource for the
+ [Apache Spark Kubernetes Operator](https://github.com/apache/spark-kubernetes-operator)
+ that runs it.
+
+Run it with:
+
+```bash
+../scripts/run-example.sh
+```
+
+which uploads the script to `s3a://warehouse/jobs/` and applies the
+`SparkApplication`.
+
+## Running your own job
+
+1. Copy `hudi_table_writer.py` and `spark-app.yaml` under new names.
+2. Edit the script; keep the two compatibility pins if Trino must read the
+ table (`hoodie.write.table.version=8`, `hoodie.write.auto.upgrade=false`)
+ and the `hoodie.datasource.hive_sync.*` options if it should appear in the
+ metastore.
+3. In the yaml: point `pyFiles` at your uploaded script (or use
+ `mainClass`+`jars` for JVM jobs), and adjust the
+ `spark.kubernetes.driverEnv.*` parameters.
+4. Upload + apply (mirroring what `run-example.sh` does):
+
+```bash
+kubectl -n hudi-lakehouse create configmap my-job-script --from-file=my_job.py
+# ... run an mc upload Job, or use `mc cp` against a port-forwarded MinIO ...
+kubectl apply -f my-spark-app.yaml
+```
diff --git a/hudi-lakehouse/local-dev/example/hudi_table_writer.py b/hudi-lakehouse/local-dev/example/hudi_table_writer.py
new file mode 100644
index 000000000000..89d4aac25d1b
--- /dev/null
+++ b/hudi-lakehouse/local-dev/example/hudi_table_writer.py
@@ -0,0 +1,87 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+"""Example Hudi write job for the hudi-lakehouse local-dev environment.
+
+Writes a partitioned Copy-on-Write table to object storage and registers it
+in the Hive Metastore via Hudi's hive-sync (thrift/hms mode), so it is
+immediately queryable from the hudi-trino chart.
+
+All endpoints/knobs come from environment variables (set in spark-app.yaml);
+copy this file together with spark-app.yaml to run your own jobs.
+"""
+import os
+
+from pyspark.sql import SparkSession
+from pyspark.sql import functions as F
+
+TABLE_NAME = os.environ.get("TABLE_NAME", "trips")
+DATABASE = os.environ.get("DATABASE", "default")
+BASE_PATH = os.environ.get("BASE_PATH", f"s3a://warehouse/hudi/{TABLE_NAME}")
+HMS_URI = os.environ.get("HMS_URI", "thrift://hive-metastore:9083")
+NUM_ROWS = int(os.environ.get("NUM_ROWS", "100"))
+
+hudi_options = {
+ "hoodie.table.name": TABLE_NAME,
+ "hoodie.datasource.write.table.type": "COPY_ON_WRITE",
+ "hoodie.datasource.write.recordkey.field": "trip_id",
+ "hoodie.datasource.write.precombine.field": "ts",
+ "hoodie.datasource.write.partitionpath.field": "city",
+ "hoodie.datasource.write.hive_style_partitioning": "true",
+ # The in-repo Trino plugin currently reads with a Hudi 1.0.x runtime,
+ # which understands table versions 6 and 8 only. Pin the write version
+ # and disable auto-upgrade so the table stays readable from Trino.
+ "hoodie.write.table.version": os.environ.get("WRITE_TABLE_VERSION", "8"),
+ "hoodie.write.auto.upgrade": "false",
+ # Register the table in the Hive Metastore (hive-sync ships inside the
+ # Hudi Spark bundle; hms mode talks thrift directly, no HiveServer2).
+ "hoodie.datasource.meta.sync.enable": "true",
+ "hoodie.datasource.hive_sync.enable": "true",
+ "hoodie.datasource.hive_sync.mode": "hms",
+ "hoodie.datasource.hive_sync.metastore.uris": HMS_URI,
+ "hoodie.datasource.hive_sync.database": DATABASE,
+ "hoodie.datasource.hive_sync.table": TABLE_NAME,
+ "hoodie.datasource.hive_sync.partition_fields": "city",
+ "hoodie.datasource.hive_sync.partition_extractor_class":
+ "org.apache.hudi.hive.MultiPartKeysValueExtractor",
+}
+
+spark = SparkSession.builder.appName(f"hudi-write-{TABLE_NAME}").getOrCreate()
+
+df = (
+ spark.range(NUM_ROWS)
+ .select(
+ F.col("id").cast("string").alias("trip_id"),
+ F.current_timestamp().alias("ts"),
+ (F.rand(seed=42) * 100).alias("fare"),
+ F.element_at(
+ F.array(F.lit("san_francisco"), F.lit("chennai"), F.lit("sao_paulo")),
+ (F.col("id") % 3 + 1).cast("int"),
+ ).alias("city"),
+ )
+)
+
+df.write.format("hudi").options(**hudi_options).mode("overwrite").save(BASE_PATH)
+
+# Second commit: upsert a slice with doubled fares to exercise mutation.
+updates = df.limit(10).withColumn("fare", F.col("fare") * 2)
+updates.write.format("hudi").options(**hudi_options).mode("append").save(BASE_PATH)
+
+count = spark.read.format("hudi").load(BASE_PATH).count()
+assert count == NUM_ROWS, f"expected {NUM_ROWS} rows after upsert, got {count}"
+print(f"DEMO_OK rows={count} table={DATABASE}.{TABLE_NAME} path={BASE_PATH}")
+
+spark.stop()
diff --git a/hudi-lakehouse/local-dev/example/spark-app.yaml b/hudi-lakehouse/local-dev/example/spark-app.yaml
new file mode 100644
index 000000000000..08a1bb6ca57e
--- /dev/null
+++ b/hudi-lakehouse/local-dev/example/spark-app.yaml
@@ -0,0 +1,61 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# SparkApplication for the Apache Spark Kubernetes Operator
+# (https://github.com/apache/spark-kubernetes-operator), submitted by
+# local-dev/scripts/run-example.sh after uploading hudi_table_writer.py to
+# s3a://warehouse/jobs/.
+#
+# To run your own job: copy this file + your script, adjust pyFiles (or
+# mainClass/jars for JVM jobs), the env block, and any spark conf.
+apiVersion: spark.apache.org/v1alpha1
+kind: SparkApplication
+metadata:
+ name: hudi-table-writer
+ namespace: hudi-lakehouse
+spec:
+ pyFiles: "s3a://warehouse/jobs/hudi_table_writer.py"
+ runtimeVersions:
+ sparkVersion: "3.5.7"
+ scalaVersion: "2.12"
+ sparkConf:
+ # Service account created by the spark-kubernetes-operator helm chart
+ # (the namespace default SA cannot manage executor pods).
+ spark.kubernetes.authenticate.driver.serviceAccountName: "spark"
+ spark.kubernetes.container.image: "hudi-lakehouse-spark:3.5"
+ spark.kubernetes.container.image.pullPolicy: "IfNotPresent"
+ spark.executor.instances: "1"
+ spark.driver.memory: "1g"
+ spark.executor.memory: "1g"
+ spark.serializer: "org.apache.spark.serializer.KryoSerializer"
+ spark.sql.extensions: "org.apache.spark.sql.hudi.HoodieSparkSessionExtension"
+ spark.kryo.registrator: "org.apache.spark.HoodieSparkKryoRegistrar"
+ # Object storage (local-dev MinIO; swap for real S3 on clusters).
+ spark.hadoop.fs.s3a.impl: "org.apache.hadoop.fs.s3a.S3AFileSystem"
+ spark.hadoop.fs.s3a.endpoint: "http://minio.hudi-lakehouse.svc.cluster.local:9000"
+ spark.hadoop.fs.s3a.access.key: "admin"
+ spark.hadoop.fs.s3a.secret.key: "password"
+ spark.hadoop.fs.s3a.path.style.access: "true"
+ # Job parameters consumed by hudi_table_writer.py.
+ spark.kubernetes.driverEnv.TABLE_NAME: "trips"
+ spark.kubernetes.driverEnv.DATABASE: "default"
+ spark.kubernetes.driverEnv.BASE_PATH: "s3a://warehouse/hudi/trips"
+ spark.kubernetes.driverEnv.HMS_URI: "thrift://hive-metastore.hudi-lakehouse.svc.cluster.local:9083"
+ spark.kubernetes.driverEnv.NUM_ROWS: "100"
+ applicationTolerations:
+ # Retain the driver pod after completion so its logs stay inspectable
+ # (run-example.sh reads them; the next run cleans the previous app up).
+ resourceRetainPolicy: Always
diff --git a/hudi-lakehouse/local-dev/manifests/hive-metastore.yaml b/hudi-lakehouse/local-dev/manifests/hive-metastore.yaml
new file mode 100644
index 000000000000..e7f48c818ecb
--- /dev/null
+++ b/hudi-lakehouse/local-dev/manifests/hive-metastore.yaml
@@ -0,0 +1,196 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Hive Metastore for LOCAL DEVELOPMENT ONLY -- Derby-backed, single replica,
+# fixed credentials. Real deployments point the hudi-trino chart at an
+# existing HMS or AWS Glue instead.
+#
+# Uses the stock apache/hive image; the container command symlinks the
+# hadoop-aws + aws-sdk jars (bundled with the image but not on the metastore
+# classpath) into $HIVE_HOME/lib so HMS can validate s3a:// table locations.
+# Note: apache/hive:3.1.3 is amd64-only; ARM minikube runs it under emulation.
+apiVersion: v1
+kind: ConfigMap
+metadata:
+ name: hive-metastore-conf
+ namespace: hudi-lakehouse
+ labels:
+ app.kubernetes.io/part-of: hudi-lakehouse
+data:
+ metastore-site.xml: |
+ <?xml version="1.0"?>
+ <configuration>
+ <property>
+ <name>metastore.thrift.uris</name>
+ <value>thrift://hive-metastore:9083</value>
+ </property>
+ <property>
+ <name>metastore.task.threads.always</name>
+ <value>org.apache.hadoop.hive.metastore.events.EventCleanerTask</value>
+ </property>
+ <property>
+ <name>metastore.expression.proxy</name>
+ <value>org.apache.hadoop.hive.metastore.DefaultPartitionExpressionProxy</value>
+ </property>
+ <property>
+ <name>metastore.warehouse.dir</name>
+ <value>s3a://warehouse/hive</value>
+ </property>
+ <property>
+ <name>javax.jdo.option.ConnectionURL</name>
+ <value>jdbc:derby:;databaseName=/opt/hive/data/metastore_db;create=true</value>
+ </property>
+ </configuration>
+ # schematool (used for one-time schema init) reads hive-site.xml, not
+ # metastore-site.xml -- both must agree on the Derby location.
+ hive-site.xml: |
+ <?xml version="1.0"?>
+ <configuration>
+ <property>
+ <name>javax.jdo.option.ConnectionURL</name>
+ <value>jdbc:derby:;databaseName=/opt/hive/data/metastore_db;create=true</value>
+ </property>
+ </configuration>
+ core-site.xml: |
+ <?xml version="1.0"?>
+ <configuration>
+ <property>
+ <name>fs.s3a.impl</name>
+ <value>org.apache.hadoop.fs.s3a.S3AFileSystem</value>
+ </property>
+ <property>
+ <name>fs.s3a.endpoint</name>
+ <value>http://minio:9000</value>
+ </property>
+ <property>
+ <name>fs.s3a.access.key</name>
+ <value>admin</value>
+ </property>
+ <property>
+ <name>fs.s3a.secret.key</name>
+ <value>password</value>
+ </property>
+ <property>
+ <name>fs.s3a.path.style.access</name>
+ <value>true</value>
+ </property>
+ </configuration>
+---
+apiVersion: v1
+kind: PersistentVolumeClaim
+metadata:
+ name: hive-metastore-data
+ namespace: hudi-lakehouse
+spec:
+ accessModes: ["ReadWriteOnce"]
+ resources:
+ requests:
+ storage: 1Gi
+---
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: hive-metastore
+ namespace: hudi-lakehouse
+ labels:
+ app.kubernetes.io/name: hive-metastore
+ app.kubernetes.io/part-of: hudi-lakehouse
+spec:
+ replicas: 1
+ # Derby allows a single process; never run old and new pods concurrently.
+ strategy:
+ type: Recreate
+ selector:
+ matchLabels:
+ app.kubernetes.io/name: hive-metastore
+ template:
+ metadata:
+ labels:
+ app.kubernetes.io/name: hive-metastore
+ spec:
+ securityContext:
+ fsGroup: 1000
+ containers:
+ - name: metastore
+ image: apache/hive:3.1.3
+ command:
+ - /bin/bash
+ - -c
+ - |
+ set -e
+ # Put the S3A filesystem (bundled with the image's Hadoop, but
+ # not on the metastore classpath) onto the classpath. The image
+ # runs as a non-root user, so $HIVE_HOME/lib is not writable --
+ # HADOOP_CLASSPATH is the supported non-root mechanism.
+ export HADOOP_CLASSPATH="$(echo "$HADOOP_HOME"/share/hadoop/tools/lib/hadoop-aws-*.jar):$(echo "$HADOOP_HOME"/share/hadoop/tools/lib/aws-java-sdk-bundle-*.jar)${HADOOP_CLASSPATH:+:$HADOOP_CLASSPATH}"
+ # Single init authority: initialize the Derby schema at the
+ # PVC-backed location on first boot (schematool reads the
+ # ConnectionURL from the mounted hive-site.xml), and tell the
+ # image entrypoint to skip its own schema init.
+ if [ ! -d /opt/hive/data/metastore_db ]; then
+ "$HIVE_HOME/bin/schematool" -dbType derby -initSchema
+ fi
+ export IS_RESUME=true
+ exec /entrypoint.sh
+ env:
+ - name: SERVICE_NAME
+ value: metastore
+ ports:
+ - name: thrift
+ containerPort: 9083
+ volumeMounts:
+ - name: conf
+ mountPath: /opt/hive/conf/metastore-site.xml
+ subPath: metastore-site.xml
+ - name: conf
+ mountPath: /opt/hive/conf/hive-site.xml
+ subPath: hive-site.xml
+ - name: conf
+ mountPath: /opt/hive/conf/core-site.xml
+ subPath: core-site.xml
+ - name: data
+ mountPath: /opt/hive/data
+ readinessProbe:
+ tcpSocket:
+ port: thrift
+ initialDelaySeconds: 20
+ periodSeconds: 10
+ resources:
+ requests:
+ cpu: 250m
+ memory: 1Gi
+ volumes:
+ - name: conf
+ configMap:
+ name: hive-metastore-conf
+ - name: data
+ persistentVolumeClaim:
+ claimName: hive-metastore-data
+---
+apiVersion: v1
+kind: Service
+metadata:
+ name: hive-metastore
+ namespace: hudi-lakehouse
+ labels:
+ app.kubernetes.io/name: hive-metastore
+spec:
+ ports:
+ - name: thrift
+ port: 9083
+ targetPort: thrift
+ selector:
+ app.kubernetes.io/name: hive-metastore
diff --git a/hudi-lakehouse/local-dev/manifests/minio-bucket-job.yaml b/hudi-lakehouse/local-dev/manifests/minio-bucket-job.yaml
new file mode 100644
index 000000000000..7e11aa7a2004
--- /dev/null
+++ b/hudi-lakehouse/local-dev/manifests/minio-bucket-job.yaml
@@ -0,0 +1,45 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# One-shot Job that creates the `warehouse` bucket in the local-dev MinIO.
+apiVersion: batch/v1
+kind: Job
+metadata:
+ name: minio-make-bucket
+ namespace: hudi-lakehouse
+ labels:
+ app.kubernetes.io/part-of: hudi-lakehouse
+spec:
+ backoffLimit: 6
+ template:
+ metadata:
+ labels:
+ app.kubernetes.io/name: minio-make-bucket
+ spec:
+ restartPolicy: OnFailure
+ containers:
+ - name: mc
+ image: quay.io/minio/mc:RELEASE.2024-11-21T17-21-54Z
+ command:
+ - /bin/sh
+ - -c
+ - |
+ set -e
+ until mc alias set local http://minio:9000 admin password; do
+ echo "waiting for minio..."; sleep 3
+ done
+ mc mb --ignore-existing local/warehouse
+ mc ls local
diff --git a/hudi-lakehouse/local-dev/manifests/minio.yaml b/hudi-lakehouse/local-dev/manifests/minio.yaml
new file mode 100644
index 000000000000..e4e9886bbc01
--- /dev/null
+++ b/hudi-lakehouse/local-dev/manifests/minio.yaml
@@ -0,0 +1,96 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# MinIO for LOCAL DEVELOPMENT ONLY -- fixed credentials, single replica.
+# Real deployments point the hudi-trino chart at real object storage instead.
+apiVersion: v1
+kind: PersistentVolumeClaim
+metadata:
+ name: minio-data
+ namespace: hudi-lakehouse
+spec:
+ accessModes: ["ReadWriteOnce"]
+ resources:
+ requests:
+ storage: 10Gi
+---
+apiVersion: apps/v1
+kind: Deployment
+metadata:
+ name: minio
+ namespace: hudi-lakehouse
+ labels:
+ app.kubernetes.io/name: minio
+ app.kubernetes.io/part-of: hudi-lakehouse
+spec:
+ replicas: 1
+ selector:
+ matchLabels:
+ app.kubernetes.io/name: minio
+ template:
+ metadata:
+ labels:
+ app.kubernetes.io/name: minio
+ spec:
+ containers:
+ - name: minio
+ image: quay.io/minio/minio:RELEASE.2024-12-18T13-15-44Z
+ args: ["server", "/data", "--console-address", ":9001"]
+ env:
+ - name: MINIO_ROOT_USER
+ value: admin
+ - name: MINIO_ROOT_PASSWORD
+ value: password
+ ports:
+ - name: s3
+ containerPort: 9000
+ - name: console
+ containerPort: 9001
+ volumeMounts:
+ - name: data
+ mountPath: /data
+ readinessProbe:
+ httpGet:
+ path: /minio/health/ready
+ port: s3
+ initialDelaySeconds: 5
+ periodSeconds: 5
+ resources:
+ requests:
+ cpu: 250m
+ memory: 512Mi
+ volumes:
+ - name: data
+ persistentVolumeClaim:
+ claimName: minio-data
+---
+apiVersion: v1
+kind: Service
+metadata:
+ name: minio
+ namespace: hudi-lakehouse
+ labels:
+ app.kubernetes.io/name: minio
+spec:
+ ports:
+ - name: s3
+ port: 9000
+ targetPort: s3
+ - name: console
+ port: 9001
+ targetPort: console
+ selector:
+ app.kubernetes.io/name: minio
diff --git a/hudi-lakehouse/local-dev/manifests/namespace.yaml b/hudi-lakehouse/local-dev/manifests/namespace.yaml
new file mode 100644
index 000000000000..023c28f1e0be
--- /dev/null
+++ b/hudi-lakehouse/local-dev/manifests/namespace.yaml
@@ -0,0 +1,21 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+apiVersion: v1
+kind: Namespace
+metadata:
+ name: hudi-lakehouse
+ labels:
+ app.kubernetes.io/part-of: hudi-lakehouse
diff --git a/hudi-lakehouse/local-dev/scripts/down.sh b/hudi-lakehouse/local-dev/scripts/down.sh
new file mode 100755
index 000000000000..04e2399d8a5a
--- /dev/null
+++ b/hudi-lakehouse/local-dev/scripts/down.sh
@@ -0,0 +1,29 @@
+#!/usr/bin/env bash
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Tears down everything up.sh created (the whole hudi-lakehouse namespace).
+set -euo pipefail
+NS=hudi-lakehouse
+
+# Delete SparkApplications FIRST, while the operator is still alive to
+# process their finalizers -- otherwise the namespace hangs in Terminating.
+kubectl -n "$NS" delete sparkapplications --all --timeout=120s 2>/dev/null || true
+
+helm uninstall hudi-trino -n "$NS" 2>/dev/null || true
+helm uninstall spark-kubernetes-operator -n "$NS" 2>/dev/null || true
+kubectl delete namespace "$NS" --ignore-not-found --timeout=300s
+echo ">>> local-dev lakehouse removed"
diff --git a/hudi-lakehouse/local-dev/scripts/run-example.sh b/hudi-lakehouse/local-dev/scripts/run-example.sh
new file mode 100755
index 000000000000..878be20ba69e
--- /dev/null
+++ b/hudi-lakehouse/local-dev/scripts/run-example.sh
@@ -0,0 +1,90 @@
+#!/usr/bin/env bash
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Runs the example Hudi write job:
+# 1. uploads local-dev/example/hudi_table_writer.py to s3a://warehouse/jobs/
+# (ConfigMap -> one-shot mc Job)
+# 2. applies the SparkApplication (Apache Spark Kubernetes Operator)
+# 3. waits for completion and prints the driver log tail
+
+set -euo pipefail
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+NS=hudi-lakehouse
+APP=hudi-table-writer
+
+echo ">>> Uploading example job script to MinIO"
+kubectl -n "$NS" create configmap example-job-script \
+ --from-file="$HERE/example/hudi_table_writer.py" \
+ --dry-run=client -o yaml | kubectl apply -f -
+
+kubectl -n "$NS" delete job upload-example-script --ignore-not-found
+kubectl -n "$NS" apply -f - <<'EOF'
+apiVersion: batch/v1
+kind: Job
+metadata:
+ name: upload-example-script
+ namespace: hudi-lakehouse
+spec:
+ backoffLimit: 4
+ template:
+ spec:
+ restartPolicy: OnFailure
+ containers:
+ - name: mc
+ image: quay.io/minio/mc:RELEASE.2024-11-21T17-21-54Z
+ command:
+ - /bin/sh
+ - -c
+ - |
+ set -e
+ mc alias set local http://minio:9000 admin password
+ mc cp /scripts/hudi_table_writer.py local/warehouse/jobs/hudi_table_writer.py
+ volumeMounts:
+ - name: scripts
+ mountPath: /scripts
+ volumes:
+ - name: scripts
+ configMap:
+ name: example-job-script
+EOF
+kubectl -n "$NS" wait --for=condition=complete job/upload-example-script --timeout=120s
+
+echo ">>> Submitting SparkApplication"
+kubectl -n "$NS" delete sparkapplication "$APP" --ignore-not-found
+kubectl apply -f "$HERE/example/spark-app.yaml"
+
+echo ">>> Waiting for the application to complete"
+for i in $(seq 1 60); do
+ STATE=$(kubectl -n "$NS" get sparkapplication "$APP" \
+ -o jsonpath='{.status.currentState.currentStateSummary}' 2>/dev/null || echo "")
+ case "$STATE" in
+ Succeeded|ResourceReleased|TerminatedWithoutReleaseResources)
+ echo ">>> Application state: $STATE"; break ;;
+ Failed|SchedulingFailure|*TimedOut|DriverEvicted)
+ echo "ERROR: application state: $STATE" >&2
+ kubectl -n "$NS" logs "${APP}-0-driver" --tail=50 || true
+ exit 1 ;;
+ *) sleep 10 ;;
+ esac
+ if [[ "$i" == 60 ]]; then echo "ERROR: timed out waiting for $APP (last state: $STATE)" >&2; exit 1; fi
+done
+
+echo ">>> Driver log tail:"
+kubectl -n "$NS" logs "${APP}-0-driver" --tail=20 | grep -v "^$" || true
+kubectl -n "$NS" logs "${APP}-0-driver" | grep "DEMO_OK" \
+ || { echo "ERROR: DEMO_OK marker not found in driver log" >&2; exit 1; }
+echo ">>> Example job succeeded"
diff --git a/hudi-lakehouse/local-dev/scripts/smoke-test.sh b/hudi-lakehouse/local-dev/scripts/smoke-test.sh
new file mode 100755
index 000000000000..7f2bd97c8735
--- /dev/null
+++ b/hudi-lakehouse/local-dev/scripts/smoke-test.sh
@@ -0,0 +1,46 @@
+#!/usr/bin/env bash
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# End-to-end smoke test on the current kube context (expects images already
+# built into the cluster daemon; see scripts/build-images.sh):
+# up.sh -> run-example.sh -> assert the table is queryable from Trino.
+
+set -euo pipefail
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+NS=hudi-lakehouse
+EXPECTED_ROWS=100
+
+"$HERE/up.sh"
+"$HERE/run-example.sh"
+
+echo ">>> Querying the table from Trino"
+TRINO_DEPLOY=deploy/hudi-trino
+ROWS=$(kubectl -n "$NS" exec "$TRINO_DEPLOY" -- \
+ trino --output-format TSV --execute "SELECT count(*) FROM hudi.default.trips" | tail -1)
+
+if [[ "$ROWS" != "$EXPECTED_ROWS" ]]; then
+ echo "FAIL: expected $EXPECTED_ROWS rows from Trino, got '$ROWS'" >&2
+ exit 1
+fi
+
+echo ">>> Partition group-by:"
+kubectl -n "$NS" exec "$TRINO_DEPLOY" -- \
+ trino --output-format ALIGNED --execute \
+ "SELECT city, count(*) AS trips, round(avg(fare), 2) AS avg_fare
+ FROM hudi.default.trips GROUP BY city ORDER BY city"
+
+echo "SMOKE TEST PASSED (${ROWS} rows served by Trino)"
diff --git a/hudi-lakehouse/local-dev/scripts/up.sh b/hudi-lakehouse/local-dev/scripts/up.sh
new file mode 100755
index 000000000000..4dfde6bfc714
--- /dev/null
+++ b/hudi-lakehouse/local-dev/scripts/up.sh
@@ -0,0 +1,96 @@
+#!/usr/bin/env bash
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Brings up the full local-dev lakehouse on the current kube context:
+# MinIO + Hive Metastore (manifests) + Apache Spark Kubernetes Operator
+# (upstream helm chart) + the hudi-trino product chart with local values.
+#
+# Prereqs: images built into the cluster daemon (scripts/build-images.sh
+# after `eval "$(minikube docker-env)"`), kubectl context pointing at the
+# target cluster.
+
+set -euo pipefail
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+ROOT="$(cd "$HERE/.." && pwd)"
+NS=hudi-lakehouse
+SPARK_OPERATOR_VERSION="${SPARK_OPERATOR_VERSION:-1.7.0}"
+
+echo ">>> Applying local-dev manifests (MinIO, Hive Metastore)"
+# A previous down.sh may have left the namespace terminating; wait it out.
+while [ "$(kubectl get namespace "$NS" -o jsonpath='{.status.phase}' 2>/dev/null)" = "Terminating" ]; do
+ echo "waiting for namespace $NS to finish terminating..."; sleep 5
+done
+kubectl apply -f "$HERE/manifests/namespace.yaml"
+kubectl apply -f "$HERE/manifests/minio.yaml"
+kubectl apply -f "$HERE/manifests/hive-metastore.yaml"
+# Jobs are immutable: delete any previous run so re-applying converges
+# (the job itself is a no-op when the bucket already exists).
+kubectl -n "$NS" delete job minio-make-bucket --ignore-not-found
+kubectl apply -f "$HERE/manifests/minio-bucket-job.yaml"
+
+echo ">>> Installing Apache Spark Kubernetes Operator (chart ${SPARK_OPERATOR_VERSION})"
+helm repo add spark-kubernetes-operator https://apache.github.io/spark-kubernetes-operator 2>/dev/null || true
+helm repo update spark-kubernetes-operator >/dev/null
+helm upgrade --install spark-kubernetes-operator \
+ spark-kubernetes-operator/spark-kubernetes-operator \
+ --version "$SPARK_OPERATOR_VERSION" \
+ --namespace "$NS"
+
+echo ">>> Installing hudi-trino chart with local-dev values"
+helm upgrade --install hudi-trino "$ROOT/charts/hudi-trino" \
+ --namespace "$NS" \
+ -f "$ROOT/charts/hudi-trino/values-local-dev.yaml" \
+ --wait --timeout 10m
+
+if [[ "${INSTALL_VLLM:-0}" == 1 ]]; then
+ # Optional: serve an open-weight model in-cluster with vLLM (GPU required)
+ # and point the gateway at it instead of the default Ollama-on-host.
+ VLLM_MODEL="${VLLM_MODEL:-Qwen/Qwen3-8B}"
+ echo ">>> Installing vllm chart (model: $VLLM_MODEL; requires a GPU node)"
+ helm upgrade --install vllm "$ROOT/charts/vllm" \
+ --namespace "$NS" \
+ --set fullnameOverride=vllm \
+ --set model="$VLLM_MODEL"
+ GATEWAY_EXTRA_ARGS=(
+ --set gateway.provider=openai-compatible
+ --set gateway.openaiCompatible.baseUrl="http://vllm.$NS.svc.cluster.local:8000/v1"
+ --set gateway.model="$VLLM_MODEL"
+ )
+else
+ GATEWAY_EXTRA_ARGS=()
+fi
+
+if [[ "${INSTALL_AGENT_GATEWAY:-1}" == 1 ]]; then
+ echo ">>> Installing hudi-agent-gateway chart with local-dev values"
+ # No --wait: readiness deliberately reflects LLM reachability, and the
+ # default local-dev provider is Ollama on the host, which may not be
+ # running yet. The pod goes Ready once `ollama serve` is reachable.
+ helm upgrade --install hudi-agent-gateway "$ROOT/charts/hudi-agent-gateway" \
+ --namespace "$NS" \
+ -f "$ROOT/charts/hudi-agent-gateway/values-local-dev.yaml" \
+ "${GATEWAY_EXTRA_ARGS[@]}"
+fi
+
+echo ">>> Waiting for MinIO + Hive Metastore readiness"
+kubectl -n "$NS" rollout status deploy/minio --timeout=300s
+kubectl -n "$NS" rollout status deploy/hive-metastore --timeout=600s
+kubectl -n "$NS" wait --for=condition=complete job/minio-make-bucket --timeout=300s
+
+echo ">>> local-dev lakehouse is up:"
+kubectl -n "$NS" get pods
+echo
+echo "Next: ./local-dev/scripts/run-example.sh (writes a Hudi table, syncs to HMS)"
diff --git a/hudi-lakehouse/scripts/build-images.sh b/hudi-lakehouse/scripts/build-images.sh
new file mode 100755
index 000000000000..a1d0b328eebe
--- /dev/null
+++ b/hudi-lakehouse/scripts/build-images.sh
@@ -0,0 +1,86 @@
+#!/usr/bin/env bash
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Builds the hudi-lakehouse container images from locally-built Maven
+# artifacts. Jars are staged into gitignored images/*/target/ directories so
+# no binaries ever enter version control.
+#
+# For minikube, run `eval "$(minikube docker-env)"` first so images land in
+# the cluster's Docker daemon.
+#
+# Usage: build-images.sh [--registry <prefix>] [--push]
+
+set -euo pipefail
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+REPO_ROOT="$(cd "$HERE/.." && pwd)"
+REGISTRY=""
+PUSH=0
+
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ --registry) REGISTRY="${2%/}/"; shift 2 ;;
+ --push) PUSH=1; shift ;;
+ *) echo "unknown arg: $1" >&2; exit 1 ;;
+ esac
+done
+
+# One Spark line for the lakehouse images; local-dev/example/spark-app.yaml
+# pins the matching image tag and spark/scala versions.
+SPARK_VERSION="3.5" SCALA_VERSION="2.12"
+SPARK_IMAGE_TAG="3.5.7-scala2.12-java17-python3-ubuntu"
+HADOOP_AWS_VERSION="3.3.4" AWS_SDK_VERSION="1.12.772"
+
+BUNDLE_JAR=$(ls "$REPO_ROOT"/packaging/hudi-spark-bundle/target/hudi-spark${SPARK_VERSION}-bundle_${SCALA_VERSION}-*.jar 2>/dev/null | grep -v sources | grep -v original | head -1 || true)
+PLUGIN_DIR=$(ls -d "$REPO_ROOT"/hudi-trino-plugin/target/trino-hudi-*/ 2>/dev/null | head -1 || true)
+
+[[ -n "$BUNDLE_JAR" ]] || { echo "ERROR: spark bundle not found; run scripts/build-jars.sh first" >&2; exit 1; }
+[[ -n "$PLUGIN_DIR" ]] || { echo "ERROR: trino plugin not found; run scripts/build-jars.sh first" >&2; exit 1; }
+
+TRINO_IMAGE="${REGISTRY}hudi-lakehouse-trino:472"
+SPARK_IMAGE="${REGISTRY}hudi-lakehouse-spark:${SPARK_VERSION}"
+GATEWAY_IMAGE="${REGISTRY}hudi-lakehouse-agent-gateway:0.1.0"
+
+# The gateway image needs no maven artifacts -- its build context is the
+# python module itself.
+echo ">>> Building $GATEWAY_IMAGE"
+docker build -t "$GATEWAY_IMAGE" "$REPO_ROOT/hudi-agent-gateway"
+
+echo ">>> Staging trino plugin: $(basename "${PLUGIN_DIR%/}")"
+rm -rf "$HERE/images/trino/target" && mkdir -p "$HERE/images/trino/target"
+cp -R "${PLUGIN_DIR%/}" "$HERE/images/trino/target/"
+echo ">>> Building $TRINO_IMAGE"
+docker build -t "$TRINO_IMAGE" "$HERE/images/trino"
+
+echo ">>> Staging spark bundle: $(basename "$BUNDLE_JAR")"
+rm -rf "$HERE/images/spark/target" && mkdir -p "$HERE/images/spark/target"
+cp "$BUNDLE_JAR" "$HERE/images/spark/target/"
+echo ">>> Building $SPARK_IMAGE"
+docker build -t "$SPARK_IMAGE" \
+ --build-arg SPARK_IMAGE_TAG="$SPARK_IMAGE_TAG" \
+ --build-arg HADOOP_AWS_VERSION="$HADOOP_AWS_VERSION" \
+ --build-arg AWS_SDK_VERSION="$AWS_SDK_VERSION" \
+ --build-arg HUDI_SPARK_BUNDLE_JAR="$(basename "$BUNDLE_JAR")" \
+ "$HERE/images/spark"
+
+if [[ "$PUSH" == 1 ]]; then
+ [[ -n "$REGISTRY" ]] || { echo "ERROR: --push requires --registry" >&2; exit 1; }
+ docker push "$TRINO_IMAGE"
+ docker push "$SPARK_IMAGE"
+ docker push "$GATEWAY_IMAGE"
+fi
+
+echo ">>> Images ready: $TRINO_IMAGE, $SPARK_IMAGE, $GATEWAY_IMAGE"
diff --git a/hudi-lakehouse/scripts/build-jars.sh b/hudi-lakehouse/scripts/build-jars.sh
new file mode 100755
index 000000000000..0c531bb861c5
--- /dev/null
+++ b/hudi-lakehouse/scripts/build-jars.sh
@@ -0,0 +1,63 @@
+#!/usr/bin/env bash
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Builds the two Maven artifacts the hudi-lakehouse images need:
+# 1. the Hudi Spark bundle (packaging/hudi-spark-bundle) -- JDK 11/17
+# 2. the Hudi Trino plugin (hudi-trino-plugin) -- JDK 23+
+#
+# Usage: build-jars.sh [--skip-bundle] [--skip-plugin]
+
+set -euo pipefail
+REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
+# The lakehouse images pin one Spark line; everything runs dockerised anyway.
+SPARK_VERSION="3.5"
+BUILD_BUNDLE=1
+BUILD_PLUGIN=1
+
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ --skip-bundle) BUILD_BUNDLE=0; shift ;;
+ --skip-plugin) BUILD_PLUGIN=0; shift ;;
+ *) echo "unknown arg: $1" >&2; exit 1 ;;
+ esac
+done
+
+MVN_ARGS=(-DskipTests -Dcheckstyle.skip=true -Dscalastyle.skip=true -Drat.skip=true -Dmaven.javadoc.skip=true -Dgpg.skip=true)
+
+if [[ "$BUILD_BUNDLE" == 1 ]]; then
+ # Profiles must be activated explicitly: activating any -D profile property
+ # disables Maven's activeByDefault profiles, so relying on defaults is fragile.
+ echo ">>> Building Hudi Spark bundle (spark${SPARK_VERSION})"
+ (cd "$REPO_ROOT" && mvn clean package -pl packaging/hudi-spark-bundle -am \
+ "-Dspark${SPARK_VERSION}" -Dflink2.1 "${MVN_ARGS[@]}")
+fi
+
+if [[ "$BUILD_PLUGIN" == 1 ]]; then
+ # Probe the JDK Maven will actually use: Maven honours JAVA_HOME, PATH may differ.
+ JAVA_MAJOR=$("${JAVA_HOME:+$JAVA_HOME/bin/}java" -version 2>&1 | sed -n 's/.*version "\([0-9]*\).*/\1/p' | head -1)
+ if [[ "${JAVA_MAJOR:-0}" -lt 23 ]]; then
+ echo "ERROR: hudi-trino-plugin requires JDK 23+ (found ${JAVA_MAJOR:-unknown})." >&2
+ echo " Set JAVA_HOME to a JDK 23 installation and re-run with --skip-bundle." >&2
+ exit 1
+ fi
+ echo ">>> Building Hudi Trino plugin (JDK ${JAVA_MAJOR})"
+ (cd "$REPO_ROOT/hudi-trino-plugin" && mvn clean package -DskipTests)
+fi
+
+echo ">>> Done. Artifacts:"
+ls -d "$REPO_ROOT"/packaging/hudi-spark-bundle/target/hudi-spark*-bundle_*.jar 2>/dev/null | grep -v sources | grep -v original || true
+ls -d "$REPO_ROOT"/hudi-trino-plugin/target/trino-hudi-*/ 2>/dev/null || true
diff --git a/hudi-lakehouse/scripts/quickstart.sh b/hudi-lakehouse/scripts/quickstart.sh
new file mode 100755
index 000000000000..4aef1b7ec5f0
--- /dev/null
+++ b/hudi-lakehouse/scripts/quickstart.sh
@@ -0,0 +1,165 @@
+#!/usr/bin/env bash
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# One-command, idempotent bring-up of the local-dev Hudi lakehouse.
+#
+# ./hudi-lakehouse/scripts/quickstart.sh [--run-example]
+#
+# Safe to re-run at any time: every step checks whether its work is already
+# done (jars built, minikube running, images present, releases installed)
+# and skips or converges accordingly.
+#
+# Steps: preflight -> minikube -> maven artifacts (spark bundle + trino
+# plugin; a JDK 23 is auto-provisioned into a gitignored .tools/ dir if none
+# is installed) -> container images (into minikube's docker daemon) ->
+# MinIO + Hive Metastore + Spark Operator + hudi-trino chart.
+#
+# Flags:
+# --run-example run the example Spark job at the end, so a Hudi table
+# is registered and ready to query from Trino
+# --rebuild-jars force the maven builds even if artifacts exist
+# --rebuild-images force the docker builds even if images exist
+
+set -euo pipefail
+HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+REPO_ROOT="$(cd "$HERE/.." && pwd)"
+RUN_EXAMPLE=0 REBUILD_JARS=0 REBUILD_IMAGES=0
+# One Spark line for the quickstart; the example manifest pins the same tag.
+SPARK_VERSION="3.5" SCALA_VERSION="2.12"
+
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ --run-example) RUN_EXAMPLE=1; shift ;;
+ --rebuild-jars) REBUILD_JARS=1; shift ;;
+ --rebuild-images) REBUILD_IMAGES=1; shift ;;
+ *) echo "unknown arg: $1" >&2; exit 1 ;;
+ esac
+done
+
+step() { printf '\n\033[1m==> %s\033[0m\n' "$*"; }
+
+# ---------------------------------------------------------------- preflight
+step "Preflight"
+MISSING=()
+for t in docker minikube helm kubectl mvn java curl; do
+ command -v "$t" >/dev/null || MISSING+=("$t")
+done
+if [[ ${#MISSING[@]} -gt 0 ]]; then
+ echo "ERROR: missing required tools: ${MISSING[*]}" >&2
+ echo " install them and re-run (macOS: brew install docker minikube helm kubectl maven temurin)" >&2
+ exit 1
+fi
+echo "all required tools present"
+
+# ----------------------------------------------------------------- minikube
+step "Minikube"
+if minikube status >/dev/null 2>&1; then
+ echo "minikube already running"
+else
+ minikube start --cpus 4 --memory 10g
+fi
+
+# ---------------------------------------------------- locate / provision JDKs
+# The trino plugin needs JDK 23+; the rest of the repo builds on the default
+# JDK. Resolution order for 23: $JDK23_HOME -> /usr/libexec/java_home (macOS)
+# -> auto-download Temurin into the gitignored .tools/ directory.
+find_jdk23() {
+ if [[ -n "${JDK23_HOME:-}" && -x "$JDK23_HOME/bin/java" ]]; then
+ echo "$JDK23_HOME"; return
+ fi
+ if [[ "$(uname)" == "Darwin" ]]; then
+ local jh
+ jh=$(/usr/libexec/java_home -v 23+ 2>/dev/null || true)
+ [[ -n "$jh" ]] && { echo "$jh"; return; }
+ fi
+ local cached
+ cached=$(ls -d "$HERE"/.tools/jdk23/*/Contents/Home "$HERE"/.tools/jdk23/*/ 2>/dev/null | head -1 || true)
+ if [[ -n "$cached" && -x "$cached/bin/java" ]]; then
+ echo "$cached"; return
+ fi
+ echo "downloading Temurin JDK 23 into $HERE/.tools/jdk23 (one-time)..." >&2
+ local os arch
+ case "$(uname)" in Darwin) os=mac ;; *) os=linux ;; esac
+ case "$(uname -m)" in arm64|aarch64) arch=aarch64 ;; *) arch=x64 ;; esac
+ mkdir -p "$HERE/.tools/jdk23"
+ curl -sL "https://api.adoptium.net/v3/binary/latest/23/ga/${os}/${arch}/jdk/hotspot/normal/eclipse" \
+ | tar xz -C "$HERE/.tools/jdk23"
+ find_jdk23
+}
+
+# ------------------------------------------------------------ maven artifacts
+step "Maven artifacts"
+BUNDLE_JAR=$(ls "$REPO_ROOT"/packaging/hudi-spark-bundle/target/hudi-spark${SPARK_VERSION}-bundle_${SCALA_VERSION}-*.jar 2>/dev/null | grep -v sources | grep -v original | head -1 || true)
+if [[ -z "$BUNDLE_JAR" || "$REBUILD_JARS" == 1 ]]; then
+ "$HERE/scripts/build-jars.sh" --skip-plugin
+else
+ echo "spark bundle present: $(basename "$BUNDLE_JAR")"
+fi
+
+PLUGIN_DIR=$(ls -d "$REPO_ROOT"/hudi-trino-plugin/target/trino-hudi-*/ 2>/dev/null | head -1 || true)
+if [[ -z "$PLUGIN_DIR" || "$REBUILD_JARS" == 1 ]]; then
+ JDK23="$(find_jdk23)"
+ echo "building trino plugin with JDK at $JDK23"
+ JAVA_HOME="$JDK23" "$HERE/scripts/build-jars.sh" --skip-bundle
+else
+ echo "trino plugin present: $(basename "${PLUGIN_DIR%/}")"
+fi
+
+# ------------------------------------------------------------------- images
+step "Container images (minikube docker daemon)"
+eval "$(minikube docker-env)"
+NEED_IMAGES=0
+docker image inspect hudi-lakehouse-trino:472 >/dev/null 2>&1 || NEED_IMAGES=1
+docker image inspect "hudi-lakehouse-spark:${SPARK_VERSION}" >/dev/null 2>&1 || NEED_IMAGES=1
+docker image inspect hudi-lakehouse-agent-gateway:0.1.0 >/dev/null 2>&1 || NEED_IMAGES=1
+if [[ "$NEED_IMAGES" == 1 || "$REBUILD_IMAGES" == 1 ]]; then
+ "$HERE/scripts/build-images.sh"
+else
+ echo "images present: hudi-lakehouse-trino:472, hudi-lakehouse-spark:${SPARK_VERSION}, hudi-lakehouse-agent-gateway:0.1.0"
+fi
+
+# ------------------------------------------------------------------ bring-up
+step "Lakehouse bring-up (MinIO, Hive Metastore, Spark Operator, hudi-trino)"
+"$HERE/local-dev/scripts/up.sh"
+
+# ------------------------------------------------------------------- example
+if [[ "$RUN_EXAMPLE" == 1 ]]; then
+ step "Example job (Spark write + hive-sync)"
+ "$HERE/local-dev/scripts/run-example.sh"
+ step "Querying from Trino"
+ kubectl -n hudi-lakehouse exec deploy/hudi-trino -- trino --output-format ALIGNED \
+ --execute "SELECT city, count(*) AS trips FROM hudi.default.trips GROUP BY city ORDER BY city"
+fi
+
+step "Done"
+cat <<'EOF'
+The local Hudi lakehouse is up. Useful commands:
+
+ # write a Hudi table and register it in the metastore (idempotent)
+ ./hudi-lakehouse/local-dev/scripts/run-example.sh
+
+ # query it from Trino
+ kubectl -n hudi-lakehouse exec deploy/hudi-trino -- \
+ trino --execute "SELECT city, count(*) FROM hudi.default.trips GROUP BY city"
+
+ # consoles
+ kubectl -n hudi-lakehouse port-forward svc/hudi-trino 8080:8080 # Trino UI
+ kubectl -n hudi-lakehouse port-forward svc/minio 9001:9001 # MinIO (admin/password)
+
+ # tear everything down
+ ./hudi-lakehouse/local-dev/scripts/down.sh
+EOF